【问题标题】:What is the different between static method and exported new instance of class静态方法和导出的新类实例有什么区别
【发布时间】:2018-05-23 13:18:10
【问题描述】:

有这2个代码sn-ps。它们之间有什么区别?在什么情况下你更喜欢一个?

export default class A {
    static methodA() {
        console.log('Method A');
    }
}

有以下用法:

import A from 'a';

function test() {
    A.methodA()
}

VS这第二个sn-p:

class A {
    methodA() {
        console.log('Method A');
    }
}

export default new A();

有以下用法:

import A from 'a';//I know that semantically I should have import a - but for the sake of this question I wrote import A.

function test() {
    A.methodA();
}

【问题讨论】:

    标签: javascript class ecmascript-6 static instance


    【解决方案1】:

    真的不多。甚至 class 也是一个对象,因此在一种情况下,您有一个对象具有属性 methodA 是一个函数,而在另一种情况下,您有一个对象具有属性 methodA 这是一个函数。

    唯一的区别是当A 是一个类时你可以做new A,但当它已经是一个实例时你不能。

    【讨论】:

      【解决方案2】:

      第二种情况是所谓的单例模式,在这种情况下,您定义一个只有一个实例的类。您更喜欢哪一个主要取决于您的用例和个人品味。如果您对更多细节感兴趣,我建议您阅读单例和一般设计模式。

      【讨论】:

      • 嗨@Mate - 谢谢,我知道这是一个单例和单例的含义。我想知道这两种方法之间是否存在差异。在第一个示例中,所有方法和属性都是静态的,而不是 - 它的行为与单例类相同。
      • 在第一个例子中,你可以实例化A。在第二个,你不能。差不多就是这样。
      猜你喜欢
      • 2011-10-30
      • 2013-07-21
      • 2012-11-02
      • 2010-11-06
      • 2011-07-11
      • 2012-08-13
      • 1970-01-01
      • 2011-04-23
      相关资源
      最近更新 更多