gpt4 book ai didi

javascript - 在不使用其名称的情况下引用静态方法内部的类

转载 作者:行者123 更新时间:2023-11-30 09:17:58 25 4
gpt4 key购买 nike

如何在 JavaScript 中不使用类名本身的情况下从静态方法引用类(类似于 PHP 的 selfself::method_name)?

例如,在下面的类中,如何在foobar方法中引用方法foo和方法bar < strong>不使用 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.
}
}

最佳答案

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

来自 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.

另请注意:

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

关于javascript - 在不使用其名称的情况下引用静态方法内部的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53716426/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com