【问题标题】:Access to a ES6 / ES7 static class variable within class and constructor在类和构造函数中访问 ES6 / ES7 静态类变量
【发布时间】:2019-11-08 17:01:41
【问题描述】:

我遇到了一个很奇怪的问题:

class AddOrSelectAddress {
    static allCountries = {
        AD: "Andorra",
        AE: "Vereinigte Arabische Emirate",
        AF: "Afghanistan",
        // ...
    };

    constructor() {
        console.log('new');
        console.log(this.allCountries); // prints "undefined"
    }
}

const myInstance = new AddOrSelectAddress();

为什么会这样?我希望this.allCountries 将包含该对象。

【问题讨论】:

  • "在非静态方法中使用 this 关键字不能直接访问静态方法。您需要使用类名来调用它们:CLASSNAME.STATIC_METHOD_NAME() 或将方法作为构造函数的属性:this.constructor.STATIC_METHOD_NAME()。" (Source) - 它用于方法,但我猜这也将计入属性。

标签: javascript ecmascript-6 static ecmascript-2016


【解决方案1】:

静态方法和属性可以通过类访问,而不是通过 this 关键字:

class AddOrSelectAddress {
    static allCountries = {
        AD: "Andorra",
        AE: "Vereinigte Arabische Emirate",
        AF: "Afghanistan",
        // ...
    };

    constructor() {
        console.log('new');
        console.log(AddOrSelectAddress.allCountries);
    }
}

const myInstance = new AddOrSelectAddress();

【讨论】:

  • 次要:它是一个属性,而不是一个方法(方法是作为函数的属性)。
  • 非常感谢。这就是解决方案。我可以以某种方式将该静态属性设为私有吗?
  • @AndréReichelt static #allCountries = {...}; 将是静态和私有的
  • @MosèRaguzzini 非常感谢!不过,非常“特殊”的语法。看起来 JS 想要更花哨。
猜你喜欢
  • 2017-04-07
  • 1970-01-01
  • 1970-01-01
  • 2018-09-25
  • 2020-10-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多