1

I have a class that I define with a constructor like this:

var Snake = function(x, y) {
    this.MoveStates = {'UP': 0, 'DOWN': 1, 'LEFT': 2, 'RIGHT': 3};
    this.moveState = this.MoveStates.DOWN;
    window.onkeydown = this.handleInput;
};

In the handleInput method I want to be able to access the move state variables, but I'm having some trouble doing so. The method looks like this:

Snake.prototype.handleInput = function(event) {
    switch (event.keyCode) {
        case 87:  //W
            this.moveState = this.MoveStates.UP;
            break;
        case 65:  //A
            this.moveState = this.MoveStates.LEFT;
            break;
        case 83:  //S
            this.moveState = this.MoveStates.DOWN;
            break;
        case 68:  //D
            this.moveState = this.MoveStates.RIGHT;
            break;
    };
};

In this method the keyword this references the window object that I bound the event to, if I'm not mistaken. How can I obtain a reference to the snake object?

2
  • window.onkeydown = this.handleInput.bind(this); Commented Mar 5, 2016 at 16:44
  • FYI Despite appearances (and the new class keyword), JavaScript does not have classes - it only simulates them. Commented Mar 5, 2016 at 16:57

2 Answers 2

2

You can use it in this way.

window.onkeydown = this.handleInput.bind(this);

Just bind the the current context while calling handleInput method on this object.

Sign up to request clarification or add additional context in comments.

Comments

0

Declare a variable at the start of the function and store this in it, then call from that:

Snake.prototype.handleInput = function(event) {
    var snake = this;
    switch (event.keyCode) {
        case 87:  //W
            snake.moveState = snake.MoveStates.UP;
            break;
        case 65:  //A
            snake.moveState = snake.MoveStates.LEFT;
            break;
        case 83:  //S
            snake.moveState = snake.MoveStates.DOWN;
            break;
        case 68:  //D
            snake.moveState = snake.MoveStates.RIGHT;
            break;
    };
};

You can then reference your snake object using snake from that point on.

1 Comment

That doesn't change anything. snake will just be a reference to window, or undefined in strict mode.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.