gpt4 book ai didi

Javascript 变量函数不保留值

转载 作者:行者123 更新时间:2023-11-30 10:25:07 28 4
gpt4 key购买 nike

这个js函数是全局变量的一部分。第一次从另一个 js 文件调用它时,它起作用了。但是第二次,从它本身来看,一切都是空的。

 Start: function () {
console.log('InactivityAlerts.Start() called ...');
if (this.active) {
if (this.IDLE_TIMEOUT != "") {
window.setInterval(this.CheckIdleTime, 1000);
console.log('started...');
}
else {
window.setTimeout(this.Start, 1000);
//an iframe sets the IDLE_TIMEOUT later, but this should continue to
//run until it is not blank.
}
}
},

当它再次调用自己时;然而,一切都是空的,包括 this.active ,它是在此之前从 Init 设置的。为什么?我怎样才能确保一切都设置正确?

感谢您的帮助

最佳答案

这是一个 this 值问题,请确保在传递函数时绑定(bind)正确的 this 值。

window.setInterval(this.CheckIdleTime.bind(this), 1000);
window.setTimeout(this.Start.bind(this), 1000);

如果您总是希望它们绑定(bind)到同一个实例,您也可以在构造时绑定(bind)它们。

function YourConstructor() {
//assumes that someFunction is defined on YourConstructor.prototype
this.someFunction = this.someFunction.bind(this);
}

或者与众所周知的实例相同:

InactivityAlerts = {
Start: function () { /*...*/ }
};

InactivityAlerts.Start = InactivityAlerts.Start.bind(InactivityAlerts);

关于Javascript 变量函数不保留值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19963176/

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