【问题标题】:Ambiguity in variables inside callbacks inside constructors构造函数内部回调内部变量的歧义
【发布时间】:2021-04-09 11:16:20
【问题描述】:
class A {
    flag = 0;  // flag 1
    constructor(timer) {
        setTimeout(function() {
            flag = 1;  // flag 2
        }, timer);
    }
}

flag 2 指的是什么变量? flag 1function() 内的本地标志?
我如何明确地引用它们中的任何一个?

【问题讨论】:

  • 标志 1 和标志 2 是不同的变量。 flag 不存在于 setTimeoutconstructor 中,所以它应该抛出一个引用错误。
  • flag = 1 这是一个全局变量。
  • @Keith 运行提供的代码时出现参考错误
  • @evolutionxbox 是的,在严格模式下它会。我相信大多数浏览器都会对一个类强制使用严格模式,但如果说使用了转译代码,它可能不会选择它,你会得到一个名为 flag 的全局变量,其值为 1..

标签: javascript class variables scope


【解决方案1】:

您需要了解 JavaScript 中的 context

[方案一:捕获this关键字]

class A{
    constructor(timer){
        var that = this; 
        that.flag = 0;
        setTimeout(function(){
            that.flag = 1;
        }, timer);
    }
}

var x = new A(200);
console.log(x.flag); // 
setTimeout(() => console.log(x.flag), 300);

[方案二:使用bind方法]

class A{
        constructor(timer){
            this.flag = 0;
            setTimeout(function(){
                this.flag = 1;
            }.bind(this), timer);
        }
    }

    var x = new A(200);
    console.log(x.flag); // 
    setTimeout(() => console.log(x.flag), 300);

[解决方案3:使用arrow func的ES6特性] ==>强烈推荐使用这个。

class A{
        constructor(timer){
            this.flag = 0;
            setTimeout(() => this.flag = 1, timer);
        }
    }
    
var x = new A(200);
console.log(x.flag)
setTimeout(() => console.log(x.flag), 300); 

【讨论】:

  • @Yunus Poonawala 这能回答你的问题吗?如果您需要任何帮助,请告诉我。
猜你喜欢
  • 1970-01-01
  • 2013-06-17
  • 2016-08-16
  • 1970-01-01
  • 1970-01-01
  • 2013-11-18
  • 1970-01-01
  • 2012-01-12
  • 2021-06-08
相关资源
最近更新 更多