考虑这个课程
class xyz {
constructor() {
this.userId = null
this.somethingInit = false
}
abc () {
// something here
// also more function
}
}
export default xyz
因此,我们使用webpack创建build.js文件,然后将其导入到index.html文件中。
现在,有人查看了我的代码,并在课后添加了此代码(说他正在将其作为单例)
function getInstance() {
if (xyz.instance === undefined) {
xyz.instance = new xyz();
}
return xyz.instance;
}
export { getInstance };
现在,我有两个问题
问题1:代替此功能
function getInstance() {
if (xyz.instance === undefined) {
xyz.instance = new xyz();
}
return xyz.instance;
}
如果我刚刚做过这样的事情
const getInstance = new xyz()
export { getInstance };
将等同于以上代码吗?
并且假设类的构造函数接受了一些参数,那么我们将如何创建单例呢?
const getInstance = new xyz()