使用ES6模块和导出默认类时,如何从同一类中的另一个方法调用静态方法?我的问题专门针对何时将类标记为默认类(与 es6调用静态方法不同)
When using ES6 modules and export default class how is it possible to call a static method from another method within the same class? My question refers specifically to when the class is marked as default (unlike es6 call static methods)
以下示例说明了不使用默认值(即 Test.staticMethod()?)时如何从非静态方法调用静态方法?
The below example illustrates how it is possible to call the static method from a non-static method when not using default, i.e. Test.staticMethod()?
export default class { static staticMethod(){ alert('static'); } nonStaticMethod(){ // will not work because staticMethod is static. // Ordinarily you would use MyClass.staticMethod() this.staticMethod(); } } 推荐答案您可以使用 this.constructor.… (如果您敢的话),但是更好的解决方案是只为您的班级命名:
You can use this.constructor.… if you dare, but the better solution would be to just name your class:
export default class MyClass { static staticMethod(){ alert('static'); } nonStaticMethod() { // Ordinarily you just use MyClass.staticMethod(); } }如果您由于某些原因不能执行此操作 1 ,那么还会有此hack:
If you cannot do this for some reason1, there's also this hack:
import MyClass from '.' // self-reference export default class { static staticMethod(){ alert('static'); } nonStaticMethod() { // Ordinarily you just use MyClass.staticMethod(); } }1:我无法想象一个好人
更多推荐
使用默认值时调用静态方法
发布评论