Javascript 静态方法和类的导出新实例之间有什么不同

Javascript 静态方法和类的导出新实例之间有什么不同,javascript,class,ecmascript-6,static,instance,Javascript,Class,Ecmascript 6,Static,Instance,有这两个代码片段。它们之间的区别是什么?在什么情况下,你更喜欢一个对另一个 export default class A { static methodA() { console.log('Method A'); } } 使用以下用法: import A from 'a'; function test() { A.methodA() } import A from 'a';//I know that semantically I should hav

有这两个代码片段。它们之间的区别是什么?在什么情况下,你更喜欢一个对另一个

export default class A {
    static methodA() {
        console.log('Method A');
    }
}
使用以下用法:

import A from 'a';

function test() {
    A.methodA()
}
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();
}
第二段:

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

export default new A();
使用以下用法:

import A from 'a';

function test() {
    A.methodA()
}
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();
}

其实不多。即使是
也是一个对象,因此在一种情况下,您有一个对象具有属性
方法a
,这是一个函数,而在另一种情况下,您有一个对象具有属性
方法a
,这是一个函数


唯一的区别是,当
A
是一个类时,您可以执行
newa
,但当它已经是一个实例时,您不能执行。

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

Hi@Mate-谢谢,我知道这是单例和单例的含义。我想知道这两种方法之间是否有区别。原因:在第一个示例中,所有方法和属性都是静态的,它的行为与单例类相同。在第一个示例中,您可以实例化
A
。第二,你不能。差不多就是这样。