I am looking for var self = this alternative plan.
var Animal = function(name){
this.name = name;
this.arr = [1,2,3,4];
this.inc = function(num){
return num + 1;
};
this.fireArr = function(){
var self = this;
this.arr.forEach(function(item){
console.log(self.inc(item));
});
};
};
var dog = new Animal("dog");
console.log(dog.fireArr());
My fiddle is here.
http://jsfiddle.net/haradashinya/TtYpc/
Do you have any idea?
Thanks in advance.
You can use
.bind()to make sure the function is called with the rightthisvalue:But imho the
self(that,_this) variable is easier to understand, because it directly states that not the normalthisvalue is used, although one would expect it (e.g. in an event handler, or jQuery’seach()). Especially on long functions, where you don’t see thebind()in the end, this is of importance. Also, some ancient browsers do not supportbind()and you would need to shim it.So, for any in-place function expressions I recommend the use of a dereferencing variable.
But it can be of great use when you have a method defined somewhere, normally using
thisto point to the current object as it is common in that context, and then the method should be used somewhere else. Instead of avar self-wrapper, you can and should usebindfor simplicity and clarity. Your example offers quite a good demo (assuming theincmethod used thethiskeyword):(although
forEach()allows us to pass a customthisargument – event attachers for example don’t)