Javascript setInterval () in OOP style not working

I'm creating a program to move an object using javascript. The functions work when they are separated, but when I try to use the OOP pattern it repeatedly throws a strange error saying

Uncaught TypeError: this.Move is not a function

      

Here is my code

function Bot(){
     this.XPos =0;
     this.YPos=0;
     this.AsyncMove=setInterval(function(){ 
         this.XPos+=10;
         this.YPos+=10;
         this.Move();
     },100);
}

Bot.prototype = {
     constructor:Bot,
     Move:function(){
         console.log(this.XPos+" ,"+this.YPos);
     }

};

      

+3


source to share


1 answer


You have to bind the current instance to an anonymous function like this



this.AsyncMove=setInterval(function(){ 
    this.XPos+=10;
    this.YPos+=10;
    this.Move();
}.bind(this),100);

      

+4


source







All Articles