简体   繁体   English

JavaScript忘记了this.something变量

[英]Javascript forgets this.something variable

I have in JavaScript class (function) with variable this.foo and function this.bar(), this.bar() I call in interval but have a small problem, JavaScript forgets this.foo and i cant use this.foo in this.bar(). 我在JavaScript类(函数)中具有变量this.foo和函数this.bar(),this.bar(),但我有一个小问题,JavaScript忘记了this.foo,在此我无法使用this.foo 。酒吧()。 Why? 为什么?

function Somethink(element) {
    this.foo = element;

    this.bar = function () {
            // And now this.foo is undefined
    }

    setInterval(this.bar, 1000)
}

It happens because setInterval calls this.bar in context of global object, not in the context of current object. 发生这种情况是因为setInterval在全局对象的上下文中而不是在当前对象的上下文中调用this.bar。 Try to call it in this way: 尝试以这种方式调用它:

var self = this;
setInterval(function () { self.bar() }, 1000);

Update As it has been pointed in comments, another option is to use bind() 更新正如评论中指出的那样,另一种选择是使用bind()

setInterval(this.bar.bind(this), 1000);

because this is the window scope when the interval runs. 因为this是间隔运行时的窗口范围。 You need to use a closure or bind() 您需要使用闭包或bind()

window.setInterval(this.bar.bind(this), 1000);
function Somethink(element) {
    var foo = element;

    var bar = function () {

    }

setInterval(bar, 1000)
}

Use variables instead. 请改用变量。 'This' changes context depending where you call it “此”会根据您在哪里调用来更改上下文

The behavior is correct. 行为是正确的。 At the time when bar() is called, this might anything. 在当时间bar()被调用, this可能什么。 The usual workaround is to assign this to a local variable: 通常的解决方法是指定this一个局部变量:

function Somethink(element) {
    var that = this; // trick
    that.foo = element;

    that.bar = function () {
            // Use "that" in here
    }

    setInterval(that.bar, 1000)
}

that will make sure the code keeps a reference to the original value of this . that将确保代码保留对this的原始值的引用。

You can do like this : 您可以这样:

function Somethink(element) {
    this.foo = element;

    this.bar = function () {
        // And now this.foo is undefined
    }
    var self = this

    setInterval(self.bar, 1000)
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM