我在文件class.js
中有一个javascript类
class counter {
constructor (params) {
this.counter;
this.params = params;
}
getCounter () {
return this.counter;
}
getParams () {
return this.params
}
}
module.exports = counter;
我正在文件a.js
初始化这个类
const counter = require('./class.js');
new counter(params); //Params is an object
现在我想使用b.js
(重要)在class.js
中访问它:
const counter = require('./class.js');
setTimeout(() => {
console.log(counter.getParams()) //Returns {}
}, 3000);
由于应用程序的复杂性,我不能使用a.js
的实例,只能使用class.js
。
有没有办法实现这个目标?我在网上查了一下,但我想我无法进行相关搜索。
您可以使用SINGLETON模式,它只允许初始化一次类,并且只创建一个将被每个人使用的对象。
Counter.js
// Store the unique object of the class here
let instance = null;
export default class Counter {
constructor (params) {
// if an object has already been created return it
if (instance) return instance;
// initialize the new object
this.params = params;
this.counter = 0;
// store the new object
instance = this;
return instance;
}
// return the unique object or create it
static getInstance() {
return instance || new Counter();
}
}
a.js
const Counter = require('./class.js');
const counterObj = new Counter(params);
b.js
const Counter = require('./class.js');
setTimeout(() => {
console.log(Counter.getInstance().getParams()) //Returns {}
}, 3000);