How to pass “this” to window setInterval

前端 未结 6 460
既然无缘
既然无缘 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:48

    In your case, you can simply:

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

    Normally, we can also have a helper method Function.prototype.bind to fix the this reference.

提交回复
热议问题