【问题标题】:'this' in an object method [duplicate]对象方法中的“this”[重复]
【发布时间】:2015-03-31 01:53:25
【问题描述】:

我是 JavaScript 新手,我正在尝试编写一个简单的游戏循环。这是我的游戏对象:

var Game = {
    timers: [],
    start: timestamp(),
    stopTimers: function() {
        consoleEntry('All timers have been stopped.');
        this.timers.length = 0;
    },
    update: function(elasped) {
        for (var i = 0; i < this.timers.length; ++i) {
            var timer = elapsed - timers[i].startTime;
            console.log('Timer: ' + timer + '. Timer interval: ' + this.timers[i].interval + '.');
            if (this.timers[i].interval <= timer) {
                this.timers[i].times--;
                this.timers[i].report = true;
                if (this.timers[i].times != 0) {
                    this.timers[i].startTime = elapsed;
                }
            }
        }
    },
    render: function() {
        for (var i = 0; i < this.timers.length; ++i) {
            if (this.timers[i].report) {
                consoleEntry('Timer: ' + this.timers[i].name + ' (' + this.timers[i].times + ' remaining).');
                this.timers[i].report = false;
                if (this.timers[i].times == 0) this.timers.splice(i, 1);
            }
        }
    },
    gameLoop: function() {
        var elapsed = timestamp() - this.start;
        this.update(elapsed);
        this.render();
        requestAnimationFrame(this.gameLoop);
    },
    startGame: function() {
        console.log(this);
        requestAnimationFrame(this.gameLoop);
    }
}

&lt;body&gt; 加载时,我调用Game.startGame();。这是我收到的错误:Uncaught TypeError: undefined is not a function。它指的是gameLoop 函数中的this.update(elapsed);。出于某种原因我不明白,当我在startGame 中执行console.log(this) 时,我得到了它所属的对象(这很棒),但是当我在gameLoop 中执行相同操作时,我得到了Window 对象.

有人知道为什么会这样吗?

谢谢!

【问题讨论】:

  • 你是在调用 new Game,然后在你刚刚创建的新对象上调用 startGame 吗?或者你真的只是在调用 Game.startGame()?
  • 字面意思 :) 我不应该,嗯?
  • 你必须将this绑定到你传递给requestAnimationFrame()的函数-requestAnimationFrame(this.gameLoop.bind(this));
  • @Jazzepi Game 变量指的是普通对象,而不是构造函数。
  • 我只是不明白为什么thisgameLoop 中返回Window

标签: javascript object methods this


【解决方案1】:

了解“this”所指内容的最简单方法是查看调用语句的点符号中的函数位于哪个对象之前。

例如,如果你说

document.createElement(..)

在函数的定义中,“this”指的是文档。

所有函数都有这样一个对象。全局函数引用window。

window.console === console; // true

所以,当你执行“requestAnimationFrame”时,“this”指的是窗口。

您可以使用函数原型函数“call”和“apply”来指定“this”所指的内容。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply

我对 window.requestAnimationFrame 不是特别熟悉,但出于您的目的,我可能会建议以下两个选项之一:

也许简单地使用“调用”就可以了

requestAnimationFrame.call(this, this.gameLoop);

或者,如果没有,闭包就可以解决问题。

requestAnimationFrame(
   (function(g){ 
       return function() { g.gameLoop(); }; 
    })(this)
);

关于 Javascript 中“this”的更多信息:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

希望这会有所帮助!

【讨论】:

  • 任何函数,无论是全局函数还是其他函数,在没有明确接收者的情况下调用都会在非严格模式下将window 作为this 的值;在严格模式下,它会得到undefined
猜你喜欢
  • 2011-12-14
  • 2020-07-08
  • 2023-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多