我有一个很奇怪的问题:
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
在那里包含对象。 最佳答案
静态方法和属性可以通过类而不是通过关键字进行访问:
class AddOrSelectAddress {
static allCountries = {
AD: "Andorra",
AE: "Vereinigte Arabische Emirate",
AF: "Afghanistan",
// ...
};
constructor() {
console.log('new');
console.log(AddOrSelectAddress.allCountries);
}
}
const myInstance = new AddOrSelectAddress();