Refer to class inside of static method without using its name

我的未来我决定 提交于 2020-01-30 02:41:53

问题


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)?

For example, in the class below, how can I refer to the method foo and the method bar inside of the foobar method without the use of FooBar.methodName?

class FooBar {
    static foo() {
        return 'foo';
    }

    static bar() {
        return 'bar';
    }

    static foobar() {
        return FooBar.foo() + FooBar.bar(); 
        // self::foo() + self::bar() would have been more desirable.
    }
}

回答1:


You can use the this keyword to refer to the object itself.

See example below:

class FooBar {
  static foo() {
    return 'foo';
  }

  static bar() {
    return 'bar';
  }

  static foobar() {
    return this.foo() + this.bar();
    // self::foo() + self::bar() would have been more desirable.
  }
}

const res = FooBar.foobar();
console.log(res);



回答2:


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



回答3:


If all of those methods are static then you can use this.

class FooBar {
    static foo() {
        return 'foo';
    }

    static bar() {
        return 'bar';
    }

    static foobar() {
        return this.foo() + this.bar();
    }
}


来源:https://stackoverflow.com/questions/53716426/refer-to-class-inside-of-static-method-without-using-its-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!