I´m littel confused with this reserve key and cases caused errors. Here a sample code where this causes errors.
var sample = {
init: function() {
this.sampleFunction0();
this.sampleFunction1();
},
sampleFunction0 : function(){
var something0, something1, something2;
something0 = this.sampleFunction2(); // works, there is no ambiguity whit 'this'
jQuery('#list li').click(function(){
something1 = this.sampleFunction2(); // ambiguity: not works, but sample.sampleFunction2(); works
something1 = sample.sampleFunction2(); // it´s works
something2 = $(this).text(); // list item val
console.log(something0) // something
console.log(something1); // something : using sample.sampleFunction2();
console.log(something2); // item val
});
},
sampleFunction1 : function(){
return 'someting';
},
sampleFunction2 : function(){
return 'something';
}
}
jQuery(document).ready(function(){
sample.init();
});
I don´t know if is correct to use sample.sampleFunction2(); instead this.sampleFunction2();
From your question I think you probably know this, but: Within the event handler,
thisrefers to the element on which you hooked the event, which is of course whythis.sampleFunction2()doesn’t work. Sothiswill be thelielement that was clicked — which is frequently quite handy.In your specific case, using
samplerather thanthisis fine, because yoursampleobject is a one-off, there won’t be more than one of it. So yes, just usesample.sampleFunction2();instead ofthis.sampleFunction2();.In cases where there may be more than one (things created via a constructor function, etc.), the typical thing to do in this case (no pun) is to define a local variable in your closure (your function you’re passing into
click) can close over:There are times when it’s useful to use jQuery’s
proxyfunction, but not in this case, because A) you’re already defining a closure, and B) you’re usingthisfor something else.proxyis useful when you’re trying to bind a function that you’ve defined elsewhere, and when you needthisto have a specific value other than the one it would normally have.More reading:
this