I'm currently learning Javascript. When I run the following code, I am getting undefined. Not sure what is wrong. Everything seems to be fine. Any help will be appreciated. Thank you.
class User{
constructor(){
this.array = [1, 2, 3]
}
static getNumber(){
return console.log(this.array)
}
}
User.getNumber()
First of all, you have to create a new instance of User with new User() or new User if you want to be able to access instance properties (such as array), because they are created with this.array = .... From the Mozilla Web Docs:
The static keyword defines a static method or property for a class, or a class static initialization block (see the link for more information about this usage). Neither static methods nor static properties can be called on instances of the class. Instead, they're called on the class itself.
Static methods are often utility functions, such as functions to create or clone objects, whereas static properties are useful for caches, fixed-configuration, or any other data you don't need to be replicated across instances.
Because getNumber is called on the constructor itself, it doesn't have access to any of the instance properties (the only one is this.array). When new User is called, it creates the this.array, but only for the instance, not the constructor.