How to pass “this” to window setInterval

前端 未结 6 489
既然无缘
既然无缘 2020-12-06 02:40

Suppose I have a function a:

function a() {
    this.b = 1;
    this.set = setInterval(function() {console.log(this.b);}, 200);
}

So when

6条回答
  •  一个人的身影
    2020-12-06 02:54

    Store a reference to this:

    function a() {
        var self = this;
        self.b = 1;
        self.set = setInterval(function() {console.log(self.b);}, 200);
    }
    

    The anonymous function that you pass to setInterval has access to any variables in its containing scope, i.e., any local variables of function a(). The magic of JS closures keeps these variables alive even after a() has completed, and each invocation of a() gets its own closure.

提交回复
热议问题