Refer to class inside of static method without using its name

前端 未结 3 365
花落未央
花落未央 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条回答
  •  -上瘾入骨i
    2021-01-15 09:11

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

提交回复
热议问题