我有一个我用这样的构造函数定义的类:
var Snake = function(x, y) {
this.MoveStates = {'UP': 0, 'DOWN': 1, 'LEFT': 2, 'RIGHT': 3};
this.moveState = this.MoveStates.DOWN;
window.onkeydown = this.handleInput;
};
在handleInput
方法中,我希望能够访问移动状态变量,但是我遇到了一些麻烦。该方法如下所示:
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;
};
};
在这个方法中,关键字this
引用我绑定事件的窗口对象,如果我没有弄错的话。我怎样才能获得对蛇对象的引用?
答案 0 :(得分:2)
答案 1 :(得分:0)
在函数的开头声明一个变量并在其中存储hours h = duration_cast<hours>(30min); // ok, h == 0h
,然后从中调用:
this
然后,您可以使用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;
};
};
从那时开始引用您的蛇对象。