Javascript 引用静态方法内部的类而不使用其名称

Javascript 引用静态方法内部的类而不使用其名称,javascript,class,static,Javascript,Class,Static,如何从静态方法引用类而不使用JavaScript中的类名本身(类似于PHP的self和self::method\u name) 例如,在下面的类中,我如何引用foo方法和foobar方法中的bar方法,而不使用foobar.methodName class FooBar { static foo() { return 'foo'; } static bar() { return 'bar'; } static fooba

如何从静态方法引用类而不使用JavaScript中的类名本身(类似于PHP的
self
self::method\u name

例如,在下面的类中,我如何引用
foo
方法和
foobar
方法中的
bar
方法,而不使用
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.
    }
}
您可以使用关键字来引用对象本身

见下例:

class FooBar{
静态foo(){
返回“foo”;
}
静态条(){
返回“bar”;
}
静态foobar(){
返回this.foo()+this.bar();
//self::foo()+self::bar()更可取。
}
}
const res=FooBar.FooBar();

控制台日志(res)如果所有这些方法都是静态的,那么您可以使用

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

    static bar() {
        return 'bar';
    }

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

是:您要问的语法是“this”

来自MDN:

正如MDN所描述的,“调用静态方法时不需要实例化 在实例化类时,它们的类和也不可调用。 静态方法通常用于为 换句话说,静态方法无法访问数据 存储在特定对象中。

注意,对于静态方法,
this
关键字引用类。 可以从中的另一个静态方法调用静态方法 和这个班一样

另请注意:

有两种方法可以调用静态方法:

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

如果它们都不是静态的,并且类有一个构造函数呢?那么你就不能,至少不那么容易。混合静态和非静态方法访问更为复杂。