【问题标题】:Call static methods when using default使用默认值时调用静态方法
【发布时间】:2017-04-27 16:31:52
【问题描述】:

当使用 ES6 模块和export default class 时,如何从同一个类中的另一个方法调用静态方法?我的问题具体指的是何时将类标记为默认值(与 es6 call static methods 不同)

下面的示例说明了如何在不使用默认值时从非静态方法调用静态方法,即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();
    }
}

【问题讨论】:

  • 据我了解-静态方法使您能够在不实例化“新类”的情况下调用该方法。另一方面,您需要键入“new Class”才能调用 nonStaticMethod()。 developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… 你能把一个实用程序类与 nonStaticMethod 类分开,然后在你的 nonStaticMethod 中调用 Utils.staticMethod() 吗?
  • 有什么原因不能在export default class 之后引入辅助名称(如export default class Foo)并引用带有名称的静态方法? (Foo.staticMethod)?这对你有用吗?
  • es6 call static methods的可能重复
  • @WiktorZychla 是的,这似乎确实有效。我不知道在使用默认值时你也可以使用类名。
  • 那么我会根据这个评论来回答。

标签: javascript oop ecmascript-6


【解决方案1】:

如果你敢,你 can use this.constructor.…,但更好的解决方案是为你的班级命名:

export default class MyClass {
    static staticMethod(){
        alert('static');
    }

    nonStaticMethod() {
        // Ordinarily you just use
        MyClass.staticMethod();
    }
}

如果由于某种原因你不能这样做1,还有这个 hack:

import MyClass from '.' // self-reference

export default class {
    static staticMethod(){
        alert('static');
    }

    nonStaticMethod() {
        // Ordinarily you just use
        MyClass.staticMethod();
    }
}

1:我无法想象一个好的

【讨论】:

    【解决方案2】:

    您可以命名导出的类并通过辅助名称引用它:

    export default class _ {
    
      static staticMethod(){
          alert('static');
      }
    
      nonStaticMethod(){
          _.staticMethod();
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-04
      • 1970-01-01
      • 1970-01-01
      • 2019-05-20
      • 2011-03-06
      • 1970-01-01
      • 2023-03-26
      • 2013-03-20
      相关资源
      最近更新 更多