全局初始化 Javascript class
Initialise Javascript class globally
我在文件 class.js
中有一个 javascript class
class counter {
constructor (params) {
this.counter;
this.params = params;
}
getCounter () {
return this.counter;
}
getParams () {
return this.params
}
}
module.exports = counter;
我正在文件 a.js
中初始化这个 class
const counter = require('./class.js');
new counter(params); //Params is an object
现在我想使用 class.js
在 b.js
中访问它(重要):
const counter = require('./class.js');
setTimeout(() => {
console.log(counter.getParams()) //Returns {}
}, 3000);
由于应用程序的复杂性,我无法使用 a.js
中的实例,只能使用 class.js
。
有什么方法可以实现吗?我在互联网上查找,但我想我无法执行相关搜索。
您可以使用 SINGLETON 模式,这将允许 class 仅初始化一次并仅创建一个供所有人使用的对象。
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);
我在文件 class.js
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
现在我想使用 class.js
在 b.js
中访问它(重要):
const counter = require('./class.js');
setTimeout(() => {
console.log(counter.getParams()) //Returns {}
}, 3000);
由于应用程序的复杂性,我无法使用 a.js
中的实例,只能使用 class.js
。
有什么方法可以实现吗?我在互联网上查找,但我想我无法执行相关搜索。
您可以使用 SINGLETON 模式,这将允许 class 仅初始化一次并仅创建一个供所有人使用的对象。
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);