Shirish Maharjan Shirish Maharjan - 10 days ago 6
Javascript Question

How to work with setInterval and constructor?

how to work with setInterval and constructor's method.
console.log is showing undefined. Can anyone explain why and how to access the variable of constructor from setInterval.

var aa=new test();
var bb;
window.onload= function(){
bb=setInterval(aa.b,1000);
}
function test(){
this.a=1;
this.b=function (){
console.log(this.a);
}
}

Answer

Try wrapping it in a function like this:

setInterval(() => aa.b(), 1000);

The reason your way doesn't work is that you pass the b function to the setInterval, but then it lose it's this reference, so this becomes the global window object, and window.a is undefined.

Wrapping it in a function make the this be aa as you invoking the function on the aa object.

If you don't want to wrap your function in another function, you can also use bind:

setInterval(aa.b.bind(aa), 1000);

Here the this is forced to be aa.