André Reichelt
André Reichelt

Reputation: 1631

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.

Upvotes: 2

Views: 276

Answers (1)

Mosè Raguzzini
Mosè Raguzzini

Reputation: 15821

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

Upvotes: 2

Related Questions