在 class 和构造函数中访问 ES6 / ES7 静态 class 变量

Access to a ES6 / ES7 static class variable within class and constructor

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

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 关键字:

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

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

const myInstance = new AddOrSelectAddress();