I sometimes assign the this pointer to a var. The benefit of it is that I don't loose the scope in anonymous callback functions. Is that a good or bad idea?
Example:
var Foo = (function($) {
var Foo = function() {
var self;
self = this;
this.init = function() {
$('#foo').click(function(e) {
self.onClick();
});
};
this.onClick = function() {
console.log(this);
};
this.init();
};
return function() {
return new Foo();
};
})(jQuery);
Thank you!
{Jim}
If you need a reference to the this value of a containing scope (which is certainly a reasonable requirement), it must be a good idea, particularly in cases where you are not in control of the function call (such as event handler functions) where it's your only option.
It's not a bad idea. Whether or not it is a good idea is mostly stylistic.
An alternate way to write your code is to hold a reference to the onClick function in the closure. However, this won't be bound for the onClick function when calling it this way. For example:
var Foo = (function($) {
var Foo = function() {
this.init = function() {
$('#foo').click(function(e) {
onClick();
});
};
var self = this; // Or use ES5's Function.prototype.bind
var onClick = this.onClick = function() {
console.log(self);
};
this.init();
};
return function() {
return new Foo();
};
})(jQuery);
I prefer this style to using self (or that or whatever name you chose) if the object's methods are all in a closure (as in your case).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With