Javascript 变量函数不保留值

Javascript variable function does not persist values

本文关键字:保留 函数 变量 Javascript      更新时间:2023-09-26

这个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.
        }
    }
},

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

感谢您的任何帮助

这是一个

this值问题,请确保在传递函数时绑定正确的this值。

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

如果您始终希望它们绑定到同一实例,也可以在构造时绑定它们。

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);