为什么这个对象未定义? [重复]

时间:2022-09-06 00:20:52

This question already has an answer here:

这个问题在这里已有答案:

I have a "class" Game definding a game and an inner "class" Snake defining a player in the game. My problem is that the member links in my Snake is showing as undefined whenever the move function is called and I can't figure out why this is.

我有一个游戏的“阶级”游戏和游戏中定义玩家的内部“阶级”Snake。我的问题是,无论何时调用move函数,我的Snake中的成员链接都显示为未定义,我无法弄清楚为什么会这样。

Here's the Game definition (with a lot stripped out for readability). If needed, I can do a complete code dump.

这是游戏定义(为了便于阅读,已经删除了很多)。如果需要,我可以进行完整的代码转储。

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]);
    }     

}

1 个解决方案

#1


0  

In a function the this keyword always refers to the parent object. In your case it's probably the window object if your code runs in a browser.

在函数中,this关键字始终引用父对象。在您的情况下,如果您的代码在浏览器中运行,它可能是窗口对象。

#1


0  

In a function the this keyword always refers to the parent object. In your case it's probably the window object if your code runs in a browser.

在函数中,this关键字始终引用父对象。在您的情况下,如果您的代码在浏览器中运行,它可能是窗口对象。