JavaScript closures inside objects: what alias should have "this" for passing into anonymous function?
We have discussion with our team about next: What correct name should have variable which will be alias for "this" in anonymous function. Simple example:
var Some开发者_JS百科Constructor = function() {
this.someProperty = 'bingo';
this.someMethod = function() {
var myObjectAlias = this;
$('a').click(function() {
alert( myObjectAlias.someProperty );
});
}
}
So my question is - What correct name should have variable "myObjectAlias"? Or what used in your code for example?
You see a lot of in code samples.
var that = this;
$('a').click(function() {
alert( that.someProperty );
});
To do that; it really doesn't matter, whatever you want.
I tend to use self
in these cases, or _self
to be explicit, has the meaning of this
without the conflicts, keeping things simple and intuitive, at least for me.
For example:
self.property
self.doSomething()
if(self.hasPickles) {
self.eat();
}
It's all a matter of preference of course, but the majority of JS developers that I've talked to find this naming style pretty intuitive, that's not to say the overall majority does, but that doesn't matter does it? Do what works for your team :)
I think sometimes it's good to use meaningful names, like "form" or "container" or whatever. In short little blocks of code is not that big a deal, but in complicated initializations for forms or dialogs there tends to be several different "interesting" objects buzzing around.
I prefer to use self
for reasons Nick Craver described.
on a tangent: consider using prototypes for your constructor:
var SomeConstructor = function() {}
SomeConstructor.prototype = {
someProperty: 'bingo',
someMethod: function() {
var self = this;
$('a').click(function() {
alert( self.someProperty );
});
}
}
The someProperty and someMethod properties can be shared among all instances, so they work fine this way. Whenever you need separate values for each instance, you should put those in the constructor itself.
精彩评论