0

I want to keep a property from the a instance and modify it in a b instance. Consider the following code

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.

rustyBucketBay
  • 4,320
  • 3
  • 17
  • 47
  • 1
    Primitive values are passed by value, not reference. You would have to pass `a` itself and then modify `this.a.a`. – kelsny Mar 31 '23 at 18:48

1 Answers1

1

You can use a getter and setter to achieve this. Update your class A and class B like this:

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

By using a getter and setter, you can pass a reference to the a property and modify it through the B instance.

Leo
  • 26
  • 2