Shirish Maharjan Shirish Maharjan - 5 months ago 40
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(){
function test(){
this.b=function (){


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.