Javascript 为什么这个对象没有定义?
我有一个定义游戏的“类”Javascript 为什么这个对象没有定义?,javascript,algorithm,oop,events,dom-events,Javascript,Algorithm,Oop,Events,Dom Events,我有一个定义游戏的“类”Game和一个定义游戏中玩家的内部“类”Snake。我的问题是,每当调用move函数时,我的Snake中的成员links就会显示为undefined,我不明白为什么会这样 以下是游戏的定义(为了便于阅读,去掉了很多)。如果需要,我可以做一个完整的代码转储 function Game ( board, numBlocks ) { // ... this.speedMap = { "fast": 100, "medium": 300, "slow": 6
Game
和一个定义游戏中玩家的内部“类”Snake
。我的问题是,每当调用move
函数时,我的Snake
中的成员links
就会显示为undefined
,我不明白为什么会这样
以下是游戏的定义(为了便于阅读,去掉了很多)。如果需要,我可以做一个完整的代码转储
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关键字始终引用父对象。在您的情况下,如果您的代码在浏览器中运行,则可能是窗口对象 this.links代码>---这是什么意思?setInterval(this.snake.move.bind(this.snake),…
@zerkms:如果你结合一个简短的解释,这应该是一个答案。将this.someVariable;
单独放在一个语句中不会“声明”请看下面的答案以了解这个是如何工作的:“到父对象”-“父对象”这个词是从哪里来的?可能是一个拼写错误;应该是s/parent/current/
@CPH4“全局”怎么样?但即使这样,整个短语仍然是不正确的。是的,全局或头部对象,如果您愿意!@zerkms为什么是“全局”?此
可以指任何嵌套范围。如果您指的是此上下文和窗口
对象,我同意“全局”是适用的。