How to pass “this” to window setInterval

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

    Just save your this reference in some other variable, that is not overridden by the window-call later on. Later you can use that variable to reference he object you started with.

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

提交回复
热议问题