0

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
  }

}
8
  • 3
    this in hello is the class itself Commented Apr 9, 2018 at 16:53
  • 4
    The premise here is flawed - You are setting this.name in an instance of a class, which static methods inherently do not have. Commented Apr 9, 2018 at 16:54
  • I understand this but accessing this.name using Example.name renders undefined. Commented Apr 9, 2018 at 16:54
  • name is an instance variable. To access it, you must create an instance (in the static method). Example.name implies that name is a static member of the class, which clearly it isn't. Commented Apr 9, 2018 at 16:55
  • Can you give me an example of this? Commented Apr 9, 2018 at 16:58

1 Answer 1

1

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.

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

4 Comments

Thank you but I need to run this instance within the static function of the class not outside. Is this possible? Meaning within static hello() I need access to this.name without acquiring it outside of the class.
@Nicos: What you want doesn't make sense. If you call a method statically there is no instance, so there is no this. Javascript can't figure out for you which instance of the class was expected. So instead of hacking your way around this, try to figure out why you want to do this and then try to fix your issue in a different way that doesn't require this hack.
Thank you, that's all I wanted to know.
"this in the context of a static class method is…", no, not the class prototype itself.

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.