This is about resolving the value of this . This is permitted as follows:
myObject.something();//this in something is myObject window.something();//this is window button.onClick=function();//this when button is clicked is button
How to solve this is already set, this is a common error with passing callbacks, as in the following example, using setTimeout
var test = function () { var me = this;// set reference to this this.sayAgain=function(){ console.log("Hi, I am "+me.toString()); } } test.prototype.toString=function(){ return "test"; } test.prototype.say = function () { console.log("Hi, I am "+this.toString()); } var t = new test(); setTimeout(t.say,50);//=window passing functon without ref to this setTimeout(function(){ t.say(); },150);//=test passing ref with function setTimeout(t.sayAgain,200);//=test using me as the saved this context
The second timeout passes closure to setTimeout, if you plan to pass the callback hundreds of times, but only create several instances of test objects, then implementing the latter (sayAgain) will work a little better.
This is because you create a closure when creating a test instance, but not when passing sayAgain as a callback, if you create many test instances and do not skip say to remove this.me and this.sayAgain from the function body many times and pass say as a closure.
You can use Function.prototype.bind , but it is not supported in IE <8, and I'm not sure if this will create a closure, as in my example, using t.say .
Hmr
source share