使用默认值时调用静态方法 [英] Call static methods when using default

查看:49
本文介绍了使用默认值时调用静态方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用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:我无法想象一个好人

这篇关于使用默认值时调用静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆