2

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.

1
  • 2
    "Static methods are not directly accessible using the this keyword from non-static methods. You need to call them using the class name: CLASSNAME.STATIC_METHOD_NAME() or by calling the method as a property of the constructor: this.constructor.STATIC_METHOD_NAME()." (Source) - It's for methods but I would guess that this will also count for properties. Commented Nov 8, 2019 at 17:04

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

4 Comments

Minor nit: it's a property, not a method (methods are properties that are functions).
Thank you very much. This is the solution. Can I somehow make that static property private?
@AndréReichelt static #allCountries = {...}; will be both static and private
@MosèRaguzzini Thank you very much! pretty "special" syntax, though. Looks like JS wants to be extra fancy.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.