gpt4 book ai didi

javascript - 在方法中丢失对象 "this"上下文

转载 作者:行者123 更新时间:2023-12-02 14:38:25 28 4
gpt4 key购买 nike

我正在做一些练习,但我在管道方法中丢失“this”上下文时遇到问题:

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:导致“this 未定义,因此它没有渲染功能”

Ad.2:如果上面有注释,“this”上下文仍然是未定义的,所以管道不是一个函数

初始化:

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。

什么原因导致上下文丢失?

最佳答案

只需绑定(bind)您想要调用管道的上下文

this.pipe = function () {  
this.render(); // 1
requestAnimationFrame(this.pipe); // 2
return this;
}.bind(this)

关于javascript - 在方法中丢失对象 "this"上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37240764/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com