【问题标题】:JavaScript Object Function Access Variable in setTimeoutsetTimeout 中的 JavaScript 对象函数访问变量
【发布时间】:2016-04-09 20:18:20
【问题描述】:

我是 JS 中 OOP 的新手。现在我正在尝试在实例中调用变量,但是如何在函数中调用它?

var foo = function() {

    this.a = 1;    // how can I call 'a' in the setTimeout() function

    this.start = function(i) {
        if (i<3){
            window.setTimeout(function() {

                console.log(a);    // this line shows undefined
                console.log(this.a);      // this line indicates 'this' is window

                i++;
                start(i);    // this one does not work as well

            }, 2000);
        }
    };
};

var bar = new foo(); 
bar.start(0);

【问题讨论】:

    标签: oop recursion settimeout


    【解决方案1】:

    只需将this 存储在函数之前的变量中即可:

    var foo = function() {
    
        this.a = 1;    // how can I call 'a' in the setTimeout() function
    
        this.start = function(i) {
            var that = this;
            if (i<3){
                window.setTimeout(function() {
    
                    console.log(that.a);      
    
                    i++;
                    that.start(i);    // this one does not work as well
    
                }, 2000);
            }
        };
    };
    
    var bar = new foo(); 
    bar.start(0);
    

    或者,您可以根据项目要求使用 ES6 的新 arrow functions

    window.setTimeout(() => {
    
        console.log(this.a);      
    
        i++;
        this.start(i);    // this one does not work as well
    }, 2000);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-07
      • 2011-01-01
      • 1970-01-01
      • 2019-09-07
      • 1970-01-01
      相关资源
      最近更新 更多