Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/449.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 为什么这个对象没有定义?_Javascript_Algorithm_Oop_Events_Dom Events - Fatal编程技术网

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为什么是“全局”?
可以指任何嵌套范围。如果您指的是此上下文和
窗口
对象,我同意“全局”是适用的。