不使用类名在静态方法中引用类

4
如何在JavaScript中从静态方法中引用类而不使用类名本身(类似于PHP的self和self::method_name)?
例如,在下面的类中,如何在foobar方法内部引用foo方法和bar方法,而不使用 FooBar.methodName?
注:self是PHP中一个指向当前类的关键字。
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.
    }
}
3个回答

3

是的:你所询问的语法是“this”。

来自 MDN:

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

如MDN所述,“静态方法在不实例化其类的情况下调用,当实例化类时也无法调用静态方法。静态方法常用于为应用程序创建实用函数。” 换句话说,静态方法没有访问特定对象中存储的数据的权限。 ...

请注意,对于静态方法,“this”关键字引用了类。您可以使用“this”从同一类中的另一个静态方法调用静态方法。

还要注意:

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

2
您可以使用this关键字来引用对象本身。
例如如下:

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
如果所有的方法都是静态的,那么您可以使用this
class FooBar {
    static foo() {
        return 'foo';
    }

    static bar() {
        return 'bar';
    }

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

如果它们全部都不是静态的,并且类有一个构造函数,那该怎么办? - Mystical
1
那你就不能这样做,至少不那么容易。混合使用静态和非静态方法访问会更加复杂。 - rorschach

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接