【问题标题】:If a class contains a reference to another class, can I access the initial class from the nested class?如果一个类包含对另一个类的引用,我可以从嵌套类访问初始类吗?
【发布时间】:2022-01-09 17:39:55
【问题描述】:

我目前正在尝试获得更多有关 Javascript 类的经验,但我不太清楚我想要实现的目标是否可行。

这是我的代码的简化版本。

class A {

  name = "ClassA"

  classB = new B()

}

class B {

  calledFromA() {
    // Is there any way I can print "ClassA" here?
  }

}

const classA = new A();
classA.classB.calledFromA();

A 类创建一个新的 B 类。然后,我想从 A 类的一个实例调用 calledFromA 方法,让它能够访问“A 类”中的所有内容。

我认为一定有办法使用this 来做到这一点?

【问题讨论】:

  • 你的课程彼此没有关系,所以不,这是不可能的。
  • “A 类创建了一个新的 B 类 ...并且它能够访问“A 类”中的所有内容”也许可以看看 inheritance?
  • 如果有人做了const a1 = new A(); a2 = new A(); a2.classB = a1.classB; const b = a2.classB; b.calledFromA() 怎么办 - 你希望打印什么名字?简而言之,不,你不能。

标签: javascript class


【解决方案1】:

通过在A 类中定义B 对象,可以访问B 类的方法和数据成员。

class A {
  name = 'empty';
  objectB = null;                  /* Object B is defined as a data member. */
  
  constructor(name, city){
    this.name = name;
    this.objectB = new B(city);    /* Object B is initialized using the constructor. */
  }
}

class B {
  city = 'empty';
  
  constructor(city)
  {
    this.city = city;
  }
}

objectA = new A('john', 'london');
console.log('Name: ', objectA.name);
console.log('City: ', objectA.objectB.city);

【讨论】:

  • 对我来说已经足够了?
  • @LeonardoPetrucci 谢谢,我希望它对你有用。 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-04-04
  • 1970-01-01
  • 2022-11-20
  • 2012-05-18
  • 2018-12-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多