我尝试以面向对象的方式组织我的代码(如 MDN 中所述)。然而,就我而言,this 指的是窗口对象。因此我收到错误
Uncaught TypeError: Cannot read property 'render' of undefined
在
this.renderer.render(this.stage);
为什么 this 引用了 window 对象,而 MDN 上却没有?
var GAME = GAME || {};
GAME.Application = function() {
this.renderer = PIXI.autoDetectRenderer(800, 600,{backgroundColor : 0x1099bb});
document.getElementById("game").appendChild(this.renderer.view);
this.stage = new PIXI.Container();
requestAnimationFrame(this.render);
}
GAME.Application.prototype.render = function() {
this.renderer.render(this.stage);
}
var app = new GAME.Application();
最佳答案
您需要绑定(bind)您的render
函数。这可能是最直接的解决方案。
requestAnimationFrame(this.render.bind(this));
或者,你也可以这样做
var context = this;
requestAnimationFrame(function() {
context.render();
});
或者您可以避免创建自由变量并使用 IIFE
requestAnimationFrame((function(context) {
context.render();
})(this)));
或者,如果您使用的是 ES6,则可以使用箭头函数
requestAnimationFrame(() => this.render());
<小时/>
您可以进行的另一个简单改进是将渲染元素传递到应用程序构造函数中
function Application(elem) {
this.renderer = ...
elem.appendChild(this.renderer.view);
}
new Application(document.getElementById("game"));
关于JavaScript 作用域问题(this),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30812757/