gpt4 book ai didi

javascript - 从对象内函数数组中的回调函数访问正确的 "this"

转载 作者:行者123 更新时间:2023-12-04 10:43:08 25 4
gpt4 key购买 nike

我正在尝试从“steps”数组中的函数内部访问“helperFunction”。显然使用“this”并不是指正确的对象,但我似乎无法找到正确的解决方案。

const bannerAnimation = {
property: 0,
steps: [
function one() {
this.property = this.helperFunction();
},
function two() {
console.log(this);
}
],
helperFunction() {
// do some calculations and return the result
return 1;
},
doSteps(steps = this.steps) {
steps.forEach(step => {
setTimeout(step, 100);
});
}
};

bannerAnimation.doSteps();

非常感谢所有帮助!

最佳答案

您可以使用 bind 来实现这一点在回调内部 setTimeout正确绑定(bind)this到正确的上下文。

const bannerAnimation = {
property: 0,
steps: [
function one() {
this.property = this.helperFunction();
},
function two() {
console.log(this);
}
],
helperFunction() {
// do some calculations and return the result
return 1;
},
doSteps(steps = this.steps) {
var self = this;
steps.forEach(step => {
setTimeout(step.bind(self), 100);
});
}
};

bannerAnimation.doSteps();

关于javascript - 从对象内函数数组中的回调函数访问正确的 "this",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59839714/

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