Asuna
Asuna

Reputation: 43

Javascript setInterval() in OOP Style Not Working

Im creating a program to move object repeatedly using javascript. Functions work when they are separated but when I try to use OOP pattern it gives a strange error repeatedly 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);
     }

};

Upvotes: 3

Views: 563

Answers (1)

prasadmadanayake
prasadmadanayake

Reputation: 1435

You should bind the current Instance to anonymous function like this

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

Upvotes: 4

Related Questions