如何使用传递的构造函数参数创建singleton类实例



我有一个文件,它是我想用作单例的类

// class.js
class A {
constructor() {}
method x
}
export default new A();

有多个文件使用它,这很好,例如:

// use1
import a from 'class.js'
a.x()
// use2
import a from 'class.js'
a.x()

然而,如果我想在初始化实例时向类传递一个参数,我该怎么做呢?

// class.js
class A {
constructor(spec) {}
method x
}
export default new A(spec);
// use1 need to do something like this
import spec from 'config.js'
import a(spec) from 'class.js' ?
a.x()
// use2
import spec from 'config.js'
import a(spec) from 'class.js'
a.x()

此外,将spec传递给所有文件确实是多余的。

有没有一种方法我只能在一个地方初始化它一次,但使它成为单例?

您可以使用一个对象,而不是一个实际上是Singleton的类。

import语句中不能传递参数。为什么不直接在class.js中导入spec呢?这样,每次导入a时,都会使用所需的构造函数参数来启动它。

// class.js
import spec from 'config.js'
class A {
constructor(spec) {}
method x
}
export default new A(spec);

最新更新