我想从a
实例中保留一个属性,并在b
实例中修改它。考虑下面的代码
class A {
constructor() {
this.a = 1
this.b = 2
}
}
class B {
constructor({ a }) { // I want to pass only the a property, not the whole a instance
this.a = a
}
addToA() {
this.a += 1
}
}
const a = new A()
const b = new B({ a: a.a })
b.AddToA()
console.log(a.a) // here I'd like to have a.a modified here and be 2, but it is 1.
Thanks in advanced.
您可以使用getter和setter来实现这一点。像这样更新A类和B类:
class A {
constructor() {
this._a = 1;
this.b = 2;
}
get a() {
return this._a;
}
set a(value) {
this._a = value;
} } class B {
constructor({ a }) {
this._a = a;
}
addToA() {
this._a.a += 1;
}
get a() {
return this._a;
} } const a = new A(); const b = new B({ a: a }); b.addToA(); console.log(a.a); // Now it will be 2
通过使用getter和setter,你可以传递a属性的引用,并通过B实例修改它。