skip to Main Content

I have two classes, A and B. I will only be setting the values of class A and I want class B variables to hold the same value as class A or have have access to all values of class A variables. In my case, class A and B should not be inherited logically. Is this possible without inheritance?.

In the below code, I have given an example where I need the value of only one variable and I could have passed the name as a method param. But, in my actual project I need to set the value of 20+ variables and it is not easy to pass around 20+ values to another class.

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

2

Answers


  1. A should have a property that links it to a B instance. Then you can use a setter to pass the name assignment through.

    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
    Login or Signup to reply.
  2. You can simultaneously assign values to both instances with Proxy:

    class B{
      print() {
        Object.entries(this).forEach(([k,v]) => console.log(k, ':', v));
      }
    }
    
    const b = new B();
    
    class A {
      constructor(b){
        return new Proxy(this, {
          set(_, prop, val, proxy){
            b[prop] = val;
            return Reflect.set(...arguments);
          }
        });
      }
      printValues() {
        b.print()
      }
    }
    
    const a = new A(b);
    
    a.name = "TOM";
    a.age = 33;
    a.printValues() // Want to Print TOM

    But better save b in the a instance with the A’s constructor argument or create b in the A’s constructor.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search