Wednesday, May 10, 2017

In Javascript, why is the "this" operator inconsistent?



In JavaScript, the "this" operator can refer to different things under different scenarios.



Typically in a method within a JavaScript "object", it refers to the current object.



But when used as a callback, it becomes a reference to the calling object.




I have found that this causes problems in code, because if you use a method within a JavaScript "object" as a callback function you can't tell whether "this" refers to the current "object" or whether "this" refers to the calling object.



Can someone clarify usage and best practices regarding how to get around this problem?



   function TestObject() {
TestObject.prototype.firstMethod = function(){
this.callback();
YAHOO.util.Connect.asyncRequest(method, uri, callBack);


}

TestObject.prototype.callBack = function(o){
// do something with "this"
//when method is called directly, "this" resolves to the current object
//when invoked by the asyncRequest callback, "this" is not the current object
//what design patterns can make this consistent?
this.secondMethod();
}
TestObject.prototype.secondMethod = function() {

alert('test');
}
}

Answer



In JavaScript, this always refers to the object invoking the function that is being executed. So if the function is being used as an event handler, this will refer to the node that fired the event. But if you have an object and call a function on it like:



myObject.myFunction();



Then this inside myFunction will refer to myObject. Does it make sense?



To get around it you need to use closures. You can change your code as follows:



function TestObject() {
TestObject.prototype.firstMethod = function(){
this.callback();
YAHOO.util.Connect.asyncRequest(method, uri, callBack);
}


var that = this;
TestObject.prototype.callBack = function(o){
that.secondMethod();
}

TestObject.prototype.secondMethod = function() {
alert('test');
}
}


No comments:

Post a Comment