如何通过构造函数参数创建单例类实例?

时间:2020-03-05 00:48:43

标签: javascript class 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,怎么办?

// 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传递到所有文件确实是多余的。

有没有办法只在一个地方初始化一次,但使它单例?

2 个答案:

答案 0 :(得分:1)

您可以使用对象而不是字面意义上为Singleton的类。

答案 1 :(得分:0)

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

// class.js
import spec from 'config.js'

class A {
  constructor(spec) {}
  method x
}
export default new A(spec);