Reputation: 539
Running into a situation where I have the following code:
class SomeClass{
constructor(){
let name="john doe"
}
static newName(){
//i want to get the "name" variable here
}
}
In my console.log when i access newName()
, I'm unable to get the reference of name
variable which I understand, the class isn't instantiated when I call the static method. So I guess my question is, what would be the best way for me to go about calling newName()
and accessing the name
variable? I can create a variable above the class let name="john doe"
and access it that way, but i'd like to figure out a way to keep everything confined in the class.
Upvotes: 1
Views: 7010
Reputation: 2295
First off, let's forget about the static
for now. So, your class should be like this:
class SomeClass {
constructor() {
this.name = "john doe";
}
newName() {
return this.name;
}
}
See the variable name
? If you declare it with let
(or var
, or const
), it would be defined as local variable in the constructor
. Thus, it can only be used inside the constructor
method. Now, if you set it with the keyword this
, it will be defined as an instance variable, therefore, it can be accessed throughout your class.
Let's see now how you can instantiate your class and call the method newName
:
let someClass = new SomeClass(),
name = someClass.newName();
If you really want to use a static method, keep in mind that everything that happens inside it, is not attached to the instance of the object.
You can read more about es6 classes here.
Upvotes: 2