问题描述
目前我有一个对象(我将其称为 A 类),其中包含另一个单独的类(B 类)作为值。我正在尝试使所有内容都可链接,但是如果我调用 B 类的方法,我将无法返回对 A 类的引用,而无需向 B 类添加一个单独的属性来引用 A 类并使其成为循环引用(所以到目前为止这不是问题,但如果可能的话我想避免它)。是否可以在引用它的类 B 上定义一个类方法?如果有帮助,A 类总是用来初始化 B 类。
用代码编辑:
class A {
constructor(age,sex){
this.b=new B
this.c=0
}
exampleMethod (){
this.c +=1 ;
return this;
}
class B {
constructor(){
this.d=0
}
exampleMethodB (){
this.d +=1
return this;
}
假设我创建了一个 A 的新实例。如果我在 A 上调用 exampleMethod(),我可以无限期地将 exampleMethod() 链接在一起。但是当我调用 A.b.exampleMethodB() 时,我无法返回链接 exampleMethod() 因为它现在正在引用 B 类的对象。我可以通过向 B 添加一个引用 A 的对象来解决这个问题,但目前我想知道是否有办法将它保留在类方法中,而不是向 B 添加另一个属性。
解决方法
您可以将 A
委托给 B
。您可以在 B
内创建 A
并使 B
设置器可链接。您可以将 parent
的 B
定义为 A
(创建它的东西)。
class B {
constructor(parent) {
this.parent = parent;
this.name = null;
}
setName(name) {
this.name = name;
return this;
}
getParent() {
return this.parent;
}
}
class A {
constructor(id) {
this.id = id;
this.b = null; // AKA child
}
create() {
this.b = new B(this);
return this.b;
}
getId() {
return this.id;
}
getB() {
return this.b; // AKA getChild
}
}
const id = new A(123).create().setName('B').getParent().getId();
console.log(id);
考虑使用外观设计模式。门面 C
将包装 B
和 A
,并将始终返回 C
的实例。 C
中的方法将委托给 A
或 B
。
外观设计模式链接https://www.geeksforgeeks.org/facade-design-pattern-introduction/
class B {
constructor(parent) {
this.name = null;
}
setName(name) {
this.name = name;
return this;
}
}
class A {
constructor() {
this.id = null;
}
setId() {
return this.id;
}
}
class C {
constructor(id) {
this.A = new A(id);
this.B = new B();
}
setName(name) {
this.B.setName(name);
return this;
}
setId(id) {
this.A.setId(id)
}
}
//You can chain like below
//new C().setName("name").setId(1);
,
继承如何?
class B {
constructor() {
this.d = 0;
}
exampleMethodB() {
this.d += 1;
return this;
}
}
class A extends B {
constructor() {
super();
this.c = 0;
}
exampleMethod() {
this.c += 1;
return this;
}
}
const a = new A();
a.exampleMethod()
.exampleMethodB()
.exampleMethod()
.exampleMethodB()
.exampleMethodB()
.exampleMethod();
console.log(a); // { d: 3,c: 3 }