Search code examples
javascriptecmascript-6staticecmascript-2016

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


I'm having a pretty strange problem:

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();

Why does that happen? I would expect, that the this.allCountries would contain the object there.


Solution

  • Static methods and properties are accessible through classes, not through this keyword:

    class AddOrSelectAddress {
        static allCountries = {
            AD: "Andorra",
            AE: "Vereinigte Arabische Emirate",
            AF: "Afghanistan",
            // ...
        };
    
        constructor() {
            console.log('new');
            console.log(AddOrSelectAddress.allCountries);
        }
    }
    
    const myInstance = new AddOrSelectAddress();