我如何从静态方法引用一个类而不在JavaScript中使用类名本身(类似于PHP的self
和self::method_name
)?
例如,在下面的类中,如何在foo
方法内部引用方法bar
和方法foobar
,而无需使用 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.
}
}
答案 0 :(得分:2)
是:您要询问的语法是“ this”。
来自MDN:
https://medium.com/@yyang0903/static-objects-static-methods-in-es6-1c026dbb8bb1
正如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
答案 1 :(得分:1)
您可以使用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 :(得分:1)
如果所有这些方法都是静态的,则可以使用this
。
class FooBar {
static foo() {
return 'foo';
}
static bar() {
return 'bar';
}
static foobar() {
return this.foo() + this.bar();
}
}