Pass this object inside the constructor to setIntervall

Good. I have a problem in JavaScript. I created a function constructor and added properties and methods that one method has when it is called to work with methods of the object environment as a basic example, since my constructor is too complex.

function Construct(){ this.alert = 'test1'; this.replace = ''; this.interval; this.run = function(){ console.log(this);//echo the constructor this.interval = setInterval(function(){ console.log(this);//echo the window object alert(this.alert); this.replace = ''; } }; } 

This fails if you read the code, which you must understand why.

how can I pass a constructor object (this) to a function of a given interval?

I tried to use external functions and pass this as arguments, but it fails, because the replacement is still what it is, and these are the runes only once why?

Please, help.

Thanks.

+1
source share
1 answer

Create a local variable self and set it to this so you can use it in your nested function:

 function Construct () { this.alert = 'test1'; this.replace = ''; this.interval; this.run = function () { var self = this; this.interval = setInterval(function () { self.replace = ''; }, 500); }; } 
+2
source

Source: https://habr.com/ru/post/905127/


All Articles