简体   繁体   English

在 Typescript 中的类之间进行通信

[英]Communicating between classes in Typescript

I'm working on a Typescript program the contains multiple classes.我正在开发一个包含多个类的 Typescript 程序。 In this application each instance requires all these classes.在这个应用程序中,每个实例都需要所有这些类。 These classes also need to communicate with one another.这些类还需要相互通信。 For example:例如:

class A{
  someNumber: number = 10;    
}

class B{
  otherNumber: number = 20;
  doSomething() {
    //check someNumber from class A
    if(someOtherNumber === 10) {
      return true;
    }
    return false;
  }
}

I came up with the following solution: Wrap the classes in a parent class then pass a reference to parent.我想出了以下解决方案:将类包装在父类中,然后将引用传递给父类。

class Parent{
  classA: A;
  classB: B;
  constructor(){
    this.classA = new A(this);
    this.classB = new B(this);
  }

}

class B{
  otherNumber: number = 20;
  parent: Parent;
  constructor(parent: Parent) {
    this.parent = parent;
  }
  doSomething() {
    //check someNumber from class A
    if(this.parent.classA.someOtherNumber === 10) {
      return true;
    }
    return false;
  }
}

Is this the correct way to achieve this goal?这是实现这一目标的正确方法吗? or is there a better solution?或者有更好的解决方案吗?

Passing around a simple plain object instead of a fake Parent class would be simpler and more intuitive:传递一个简单的普通对象而不是一个假的Parent类会更简单、更直观:

class A { ... }
class B { ... }
export const instances = {
  a: new A(),
  b: new B()
};
// other files:
import { instances } from './instances';
// use instance.a, instance.b

But it's a bit weird to define a class that's only used once.但是定义一个只使用一次的类有点奇怪。 Using plain objects for a and b might make things even cleaner.ab使用普通对象可能会使事情变得更干净。

export const a = {
  someNumber: 10,
};
export const b = {
  someNumber: 20,
  doSomething() {
    // ...
  }
};
// or export them together in a single object

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

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