Home > Blockchain >  Nodejs Calling the class multiple times
Nodejs Calling the class multiple times

Time:12-04

I have simple class like that;

class Foo {
    constructor() {
        this.datas = {}
    }

    set(key, data) {
        return this.datas[key] = data
    }

    get(key) {
        return this.datas[key]
    }
}

module.exports = Foo

I am adding some data to datas veriable first. But when I call same class in the next time, veriable is not saving like that;

const foo1 = Foo()
foo1.set('a',[1,2,3])
const foo2 = Foo()
var aData = foo2.get('a')
console.log(aData)

But data not getting. How can I fix it?

CodePudding user response:

The datas property that you defined in the Foo class is not being saved between instances of the class, because it is defined inside the constructor function. This means that every time you create a new Foo object with const foo = new Foo(), a new datas property will be created for that object, and it will not be shared with other instances of the Foo class.

if you want to shared by all instances of the class.refer Javascript ES6 shared class variable

CodePudding user response:

You can pass your object into another class constructor,

https://stackblitz.com/edit/node-k3vqtp?file=index.js

or use global variable

global.foo = new Foo();
global.foo.set('a', [1, 2, 3]);

or use package like InversifyJS to inject the class

...
@injectable()
export default class A implements IA {
  private _foo!: Foo;
  public get foo(): Foo {
    return this._foo;
  }
  public set foo(v: Foo) {
    this._foo = v;
  }

  constructor(
    @inject(TYPES.Foo) foo: Foo,
  ) {
    this.foo = foo;
  }
...

Due to the limited information from your question, here only list some options. You can look for the best way to fit your scenario.

  • Related