Mohsin Mohsin - 11 months ago 92
Javascript Question

prototype printing undefined in console with setInterval function in javascript

I am trying to print something in prototype function using setInterval it's showing undefined in console.



function newFunc(){
this.name = "this is person name";
this.Age = "16 Years";
}

newFunc.prototype.init = function(){
setInterval(function(){newFunc.prototype.xyz()}, 1000);
}


newFunc.prototype.xyz = function(){
console.log(this.Age);
}


var abc = new newFunc();

abc.init();




Answer Source

Its also inside the function.so apply with this.xyz() .this declare with some variable and apply into the setInterval(copy.xyz())

Why use this

this.xyz() only applicable on newFunc.prototype.init.Not ah setInteval(function (){}).These Two function are seperate. so to passing with setInterval function .We need one variable.So only i was declare with var copy

function newFunc(){           
           this.name = "this is person name";
           this.Age = "16 Years";           
       }

       newFunc.prototype.init = function(){  
       var copy = this;//in `this` applicable only  newFunc.prototype.init.it copy from another variable
           setInterval(function(){//in this function are different.
             copy.xyz()//passing variable and excute the function
           
           }, 1000);           
       }
       
       
       newFunc.prototype.xyz = function(){           
           console.log(this.Age);           
       }


       var abc = new newFunc();
        
        abc.init();