简体   繁体   English

Nodejs多次调用class

[英]Nodejs Calling the class multiple times

I have simple class like that;我有这样简单的 class;

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.我首先将一些数据添加到datas veriable 中。 But when I call same class in the next time, veriable is not saving like that;但是,当我下次调用相同的 class 时,可验证的并不是那样保存;

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?我该如何解决?

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.您在Foo class 中定义的数据属性不会在 class 的实例之间保存,因为它是在构造函数 function 中定义的。这意味着每次您使用const foo = new Foo()创建一个新的 Foo object 时,一个将为该 object 创建新的数据属性,并且不会与 Foo class 的其他实例共享。

if you want to shared by all instances of the class.refer Javascript ES6 shared class variable如果要由 class 的所有实例共享。请参阅Javascript ES6 共享 class 变量

You can pass your object into another class constructor,您可以将 object 传递给另一个 class 构造函数,

https://stackblitz.com/edit/node-k3vqtp?file=index.js 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或者像 InversifyJS 一样使用package来注入 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.您可以寻找适合您的场景的最佳方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM