Javascript 变量函数不保留值

标签 javascript

这个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/

相关文章:

javascript - Bootstrap 3 : delete confirm dialog box not work

javascript - 如何将图表的 Y 轴放在图表的右侧

javascript - JQuery 单击和悬停功能无法正常工作

JavaScript toLocaleTimeString() - 在 Firefox 中无法正常工作

javascript - 使用字符串变量访问 JavaScript 模块方法

javascript - 仅在 IE 中使用 jQuery 发布数据时出现错误请求错误

javascript - 如何从单独的表单中预填充数据电子邮件

c# - 我可以在 outclick 事件后进行文本框验证吗?

javascript - Javascript中负数的舍入

javascript - 运行 jquery gallery 会使链接无法点击