Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the object of the function javascript

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?

like image 866
Bear Avatar asked Jul 07 '26 02:07

Bear


2 Answers

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);
like image 20
Tikhon Jelvis Avatar answered Jul 09 '26 16:07

Tikhon Jelvis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!