0

I'm trying to call my method Move(); inside the object MySnake using setInterval:

function Snake()
{
    this.Start = function(Speed)
    {
        this.Movement = setInterval(function(){
            this.Move();
        },Speed);
    }
}
var MySnake = new Snake();
MySnake.Start(400); //Doesn't work

and this isn't working. But when I call the method through the instance 'MySnake':

function Snake() 
{
    MySnake.Start = function(Speed)
    {
        this.Movement = setInterval(function(){
            MySnake.Move();
        },Speed);
    }
}
var MySnake = new Snake();
MySnake.Start(400); //Works

I wan't the one whit 'this' keyword to work

Adir Tuval
  • 21
  • 2

2 Answers2

3

This is because this is defined by the caller in JavaScript. The easiest solution is to store it in another variable:

function Snake()
{

    this.Start = function(Speed)
    {
        var that = this;
        this.Movement = setInterval(function(){
            that.Move();
        },Speed);
    }
}
var MySnake = new Snake();
MySnake.Start(400); //Work

Here is a working jsfiddle. In your example, the inner this is the global window.


Another solution would be to bind this in the function to the local this, as shown in this second jsfiddle:

function Snake()
{
    this.Move = function() { document.body.innerHTML += '.'; };

    this.Start = function(Speed)
    {
        this.Movement = setInterval((function(){
            this.Move();
        }).bind(this),Speed);
    }
}
var MySnake = new Snake();
MySnake.Start(400); //Work

But this one is harder to read.

bfontaine
  • 18,169
  • 13
  • 73
  • 107
0

when you do this.move(); "this" is inside anonymous function passed into the setInterval method, hence you will get an error.

function Snake()
{

    this.Start = function(Speed)
    {
        var _this = this;
        this.Movement = setInterval(function(){
            _this.Move();
        },Speed);
    }
}

var MySnake = new Snake();

MySnake.Start(400)

This will work since the reference to the object is captured by closure created by the callback for setInterval.

MIdhun Krishna
  • 1,739
  • 1
  • 13
  • 31