【发布时间】:2015-07-29 04:45:34
【问题描述】:
我有一个定义游戏的“类”Game 和一个定义游戏中玩家的内部“类”Snake。我的问题是,每当调用move 函数时,Snake 中的成员links 就会显示为undefined,我不知道这是为什么。
这是Game 的定义(为了便于阅读,去掉了很多内容)。如果需要,我可以进行完整的代码转储。
function Game ( board, numBlocks )
{
// ...
this.speedMap = { "fast": 100, "medium": 300, "slow": 600 };
this.curSpeed;
this.mover;
// ...
this.Snake = function ( game )
{
this.links;
this.dx;
this.dy;
this.createNew = function ( )
{
this.dx = 0; this.dy = 0;
this.links = [];
// ...
}
this.move = function ( )
{
console.log(this.links); // test
// ^ That is printing 'undefined'! Didn't I initialize it in 'createNew', though????
// ...
}
}
this.startNew = function ( spd )
{
// ...
this.snake = new this.Snake(this);
this.snake.createNew();
// ...
this.curSpeed = spd;
this.mover = setInterval(this.snake.move, this.speedMap[this.curSpeed]);
}
}
【问题讨论】:
-
this.links;--- 这是什么意思? -
setInterval(this.snake.move.bind(this.snake), ... -
@zerkms:如果你把它和一个简短的解释结合起来,那应该是一个答案。
-
将
this.someVariable;单独放在一个声明中不会“声明”它或任何类似的东西,所以不要这样做。 -
查看此答案以了解
this的实际工作原理:stackoverflow.com/questions/13441307/…
标签: javascript algorithm oop events dom-events