我正在做一些练习,我有失败的问题"这个"管道方法中的上下文:
function Main() {
// something
this.render = function () {
this.groups.forEach(function(g){
renderGroup(g);
});
return this;
};
// something
this.pipe = function () {
this.render(); // 1
requestAnimationFrame(this.pipe); // 2
return this;
};
// something
}
Ad.1:原因"这是未定义的,所以它没有渲染功能"
Ad.2:如果上述评论,仍然是"这" context是未定义的,因此pipe不是函数
初始化:
function init () {
var m = new Main();
requestAnimationFrame(m.pipe);
}
window.onload = function () {
init();
}
完整目标代码:
function Main() {
this.canvas = document.createElement("canvas");
this.canvas.width = 1366;
this.canvas.height = 768;
this.canvas.style.width = this.canvas.width + "px";
this.canvas.style.height = this.canvas.height + "px";
this.groups = [];
window.app = {};
this.grain = 30 * 1000 * 60;
this.grainWidth = 30;
this.getGroups = function () {return this.groups;}
this.render = function () {
this.groups.forEach(function(g){
renderGroup(g);
});
return this;
};
this.ctx = this.canvas.getContext("2d");
this.pipe = function () {
this.render();
requestAnimationFrame(this.pipe);
return this;
};
document.body.appendChild(this.canvas);
registerEvents();
}
renderGroup是forEach。
导致背景丢失的原因是什么?
答案 0 :(得分:1)
只需使用
绑定要调用管道的上下文this.pipe = function () {
this.render(); // 1
requestAnimationFrame(this.pipe); // 2
return this;
}.bind(this)
答案 1 :(得分:1)
也许是这样的?
requestAnimationFrame(this.pipe.bind(this));
JavaScript函数在被调用时定义this
。您使用pipe
作为回调,因此它的上下文变为window
,因为它是从window.requestAnimationFrame
调用的。