Today I ran into a very odd problem using Javascript's prototype
and the this
reference.
Basically, I have two objects. One object makes use of a div
element and makes is possible to register an onclick
event on the div
. The other object makes use of this functionality and registers the onclick
event using the first object.
Here is the code:
My first object, which takes care of the div
:
DivObject = function() {};
DivObject.prototype.setClickListener = function(clickListener){
document.getElementById("myDiv").onclick = function(e){
clickListener(e);
};
};
My second object uses this functionality:
MainObject = function(){
this.myString = "Teststring";
this.divObj = new DivObject();
this.divObj.setClickListener(this.handleClick);
};
MainObject.prototype.handleClick = function(e){
// do something with e
};
The problem is, that inside MainObject.prototype.handleClick
, the this
reference refers to the window
object, not to the MainObject
. So, console.log(this)
inside this function logs [Object window]
.
You can see this behaviour on jsfiddle.
As a workaround, I use the setClickListener
function as follows:
var thisRef = this;
this.divObj.setClickListener(function(e){
thisRef.handleClick(e);
});
Now, the this
reference in my handleClick
function refers to my MainObject
(as I want it to be).
See this workaround on jsfiddle.
My questions are:
Why does the this
reference one time refer to the window
object and one time to the this
reference of my object? Is it overridden somewhere? I always thought using this
in my object I can be sure that it is really the this
reference of my object? Is the workaround I am using now the way how this problem should be solved or are there any other, better way to handle this case?