3

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);
     }

};
John Saunders
  • 160,644
  • 26
  • 247
  • 397
Asuna
  • 43
  • 5
  • Possible duplicate: http://stackoverflow.com/questions/2130241/pass-correct-this-context-to-settimeout-callback – hindmost May 08 '15 at 06:57
  • possible duplicate of [Instantiating a class and then pass it to setInterval](http://stackoverflow.com/questions/29065901/instantiating-a-class-and-then-pass-it-to-setinterval) – OddDev May 08 '15 at 06:57
  • possible duplicate of http://stackoverflow.com/questions/10944004/how-to-pass-this-to-window-setinterval – Logain May 08 '15 at 07:13

1 Answers1

4

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);
prasadmadanayake
  • 1,415
  • 15
  • 23