Javascript 设置在requestAnimationFrame中更正此值
我有一个应用程序对象构造函数,如下所示:Javascript 设置在requestAnimationFrame中更正此值,javascript,html5-canvas,requestanimationframe,Javascript,Html5 Canvas,Requestanimationframe,我有一个应用程序对象构造函数,如下所示: var app = function(loadedsettings) { return { init: function() { this.loop(); }, loop: function() { this.update(); window.requestAnimationFrame(this.loop
var app = function(loadedsettings) {
return {
init: function() {
this.loop();
},
loop: function() {
this.update();
window.requestAnimationFrame(this.loop);
},
update: function() {
//loop through settings and call update on every object.
},
settings: [
//array of settings objects, all with update methods.
]
};
}
那么当我这样做的时候:
var theApp = app(settings);
theApp.init();
我得到:
Uncaught TypeError: Object [object global] has no method 'update'
因为在调用requestAnimationFrame时,循环函数中的this值设置为window
有人知道如何使用'theApp'对象作为此值调用RequestAnimationInframe吗 您需要缓存对该
的引用
:
var app = function(loadedsettings) {
var self = this;
return {
init: function() {
self.loop();
},
loop: function() {
self.update();
window.requestAnimationFrame(self.loop);
},
** snip **
...
您可以创建绑定函数(使用固定的
this
),并将其传递给requestAnimationFrame:
var app = function(loadedsettings) {
return {
init: function() {
this.loop();
},
loop: function() {
this.update();
window.requestAnimationFrame(this.loop.bind(this));
},
update: function() {
//loop through settings and call update on every object.
},
settings: [
//array of settings objects, all with update methods.
]
};
}
我认为支持requestAnimationFrame的浏览器也将支持Function.prototype.bind,但如果您遇到不支持的浏览器,则会提供polyfills。谢谢您的回答,但是,如果调用构造函数时没有新运算符,我想在将其分配给self时,这将是一个窗口。。?