Nicos
Nicos

Reputation: 1

Access class scope within static function ES6

How does one access this scope with a static function of a class? Am I missing something here?

class Example {

  constructor() {
    this.name = 'Johan';
  }

  static hello(){

    // How to access `this` scope here in the static

    Example.name; // Undefined
    this.name; // Undefined
  }

}

Upvotes: 0

Views: 401

Answers (1)

Matt Morgan
Matt Morgan

Reputation: 5313

The commenters are correct, this in the context of a static class method is the class itself.

When you create an instance of the class using new, that instance is its own this. You can access properties and methods on the instance through this.

See the examples below:

class Example {

  constructor() {
    this.name = 'Johan';
  }

  static hello(){
    console.log(this);
    console.log(this.name);
  }

}

Example.hello();  // logs out the above class definition, followed by the name of the class itself.

let x = new Example();
console.log(x.name);  // logs out 'Johan'.

x.hello(); // x does not have `hello()`.  Only Example does.

Upvotes: 1

Related Questions