Refer to class inside of static method without using its name

前端 未结 3 363
花落未央
花落未央 2021-01-15 08:20

How can I refer to a class from a static method without using the class name itself in JavaScript (similar to PHP\'s self and self::method_name)?<

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-15 09:08

    Yes: the syntax you're asking about is "this".

    From MDN:

    https://medium.com/@yyang0903/static-objects-static-methods-in-es6-1c026dbb8bb1

    As MDN describes it, “Static methods are called without instantiating their class and are also not callable when the class is instantiated. Static methods are often used to create utility functions for an application.” In other words, static methods have no access to data stored in specific objects. ...

    Note that for static methods, the this keyword references the class. You can call a static method from another static method within the same class with this.

    Also note:

    There are two ways to call static methods:

    Foo.methodName() 
    // calling it explicitly on the Class name
    // this would give you the actual static value. 
    
    this.constructor.methodName()
    // calling it on the constructor property of the class
    // this might change since it refers to the class of the current instance, where the static property could be overridden
    

提交回复
热议问题