Dev Aggarwal
Dev Aggarwal

Reputation: 783

Initialise Javascript class globally

I have a javascript class in file class.js

class counter {

  constructor (params) {
    this.counter;
    this.params = params;

  }

  getCounter () {
    return this.counter;
  }

  getParams () {
    return this.params
  }

}
module.exports = counter;

I am initializing this class in file a.js

const counter = require('./class.js');

new counter(params); //Params is an object

Now I want to access this in b.js using class.js (IMPORTANT):

const counter = require('./class.js');

setTimeout(() => {
  console.log(counter.getParams()) //Returns {}
}, 3000);

Due to complexity of application, I cannot use instance from a.js and must use class.js only.

Is there any way of achieving this? I looked up on internet but I guess I couldn't perform a relevant search.

Upvotes: 2

Views: 1243

Answers (1)

Orelsanpls
Orelsanpls

Reputation: 23505

You can use of the SINGLETON pattern, which will allow to initialize the class only once and create only one object that will be used by everybody.


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);

Upvotes: 1

Related Questions