全局初始化Javascript类

时间:2019-03-11 14:06:40

标签: javascript class es6-class

我在文件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

有什么办法可以做到这一点?我在互联网上查了一下,但我想我无法执行相关搜索。

1 个答案:

答案 0 :(得分:1)

您可以使用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);