Suppose I have a obj called myObj and it has a function test
MyObj.prototype.test = function(){
alert(this);
}
And I set the timer:
setInteravl(myObj.test,1000);
As this depends entirely on how you called the function, this refers to window instead of myObj in the alert statement
What should I do if I need the myObj reference instead?
Wrap it in an anonymous function:
var myObj = new MyObj();
setInterval(function() {myObj.test();}, 1000);
Or in modern implementations, bind it.
var myObj = new MyObj();
setInterval(myObj.test.bind(myObj), 1000);
You can wrap it in a function:
setInteravl(function () {myObj.test()} ,1000);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With