Skip to content Skip to sidebar Skip to footer

Access Constructor Var In Static Method (es6)

Running into a situation where I have the following code: class SomeClass{ constructor(){ let name='john doe' } static newName(){ //i want to get the '

Solution 1:

First off, let's forget about the static for now. So, your class should be like this:

classSomeClass {
  constructor() {
    this.name = "john doe";
  }

  newName() {
    returnthis.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.

Post a Comment for "Access Constructor Var In Static Method (es6)"