将类变量从一个类传递到另一个类

问题描述 投票:0回答:1

我有两个班级,

A
B
。我只会设置
class A
的值,并且希望
class B
变量保持与 A 类相同的值,或者可以访问
class A
变量的所有值。就我而言,A类和B类在逻辑上不应该被继承。如果没有继承,这可能吗?.

在下面的代码中,我给出了一个示例,其中我只需要一个变量的值,并且我可以将

name
作为方法参数传递。但是,在我的实际项目中,我需要设置 20 多个变量的值,并且将大约 20 多个值传递给另一个类并不容易。

class B {
  name: string
  age: number

  print() {
    console.log(this.name);
  }
}

const b = new B();

class A {
  name: string;
  age: number;

  printValues() {
    b.print()
  }
}

const a = new A();
a.name = "TOM"
a.printValues() // Want to Print TOM

javascript
1个回答
0
投票

A
应该有一个将其链接到
B
实例的属性。然后您可以使用 setter 来传递
name
赋值。

class B {
  name: string
  age: number

  print() {
    console.log(this.name);
  }
}

const b = new B();

class A {
  age: number;
  b: B;

  constructor(b) {
    this.b = b;
  }

  get name() {
    return this.b.name;
  };

  set name(new_name) {
    this.b.name = new_name;
  }

  printValues() {
    this.b.print()
  }
}

const a = new A(b);
a.name = "TOM"
a.printValues() // Want to Print TOM

© www.soinside.com 2019 - 2024. All rights reserved.