【问题标题】:Why is this object undefined? [duplicate]为什么这个对象未定义? [复制]
【发布时间】: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


【解决方案1】:

在函数中,this 关键字总是指向父对象。在您的情况下,如果您的代码在浏览器中运行,它可能是 window 对象。

【讨论】:

  • “到父对象”---你从哪里得到“父”这个词?
  • 可能是错字;应该是s/parent/current/
  • @CPH4 “全球”怎么样?但即便如此,整个短语仍然是不正确的。
  • 是的,如果您愿意,可以选择全局或头部对象!
  • @zerkms 为什么是“全球”? this 可以引用任何嵌套范围。如果您指的是这个上下文和window 对象,我同意“全局”是适用的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-07
  • 2016-09-24
  • 2012-08-09
  • 2021-01-14
  • 2015-12-16
  • 2017-07-23
相关资源
最近更新 更多