Wednesday 29 February 2012

Javascript: Function's Parent is DomWindow when referring to 'this'

If you have created an eventlistener or a setInterval and passed in a function which belongs to an Object you may find that the function does not refer to it parent object with 'this but it refers to the DomWindow.

To fix this you need to wrap the function with another function and pass in the parent object:

Example: {
str:"hello world",
start: function() {
var t = this;
this.timer = setInterval(function(){t.todo();},1000);
},

todo : function() {
alert(this.str);
}
};

In this Example I create an object which has a string with the value 'hello world'. I then create a setInterval and pass 'this' (parent object) to the 'todo' function via a wrapper function.

No comments:

Post a Comment