0

I have a really big urge to do something like this:

class A {
    constructor(){}
    age() { return 15; }
}

class B {
    constructor() {
        this.a = new A();
    // DO SOMETHING THAT THIS IS POSSIBLE:
    }
}

B b = new B();
b.age();

How to expose the method as if it was object b's own method? I need to do this for every method of a property, regardless of number and name.

NOTE: I can't use inheritance.

Shocky2
  • 444
  • 6
  • 22

2 Answers2

3

extends provides inheritance functionality:

class A {
  constructor(){}
  age() { return 15; }
}

class B extends A {
  constructor() {
    super()
  }
}

const b = new B();

console.log(b.age());

I'd be interested to learn why you can't use normal inheritance. Here's a way to manually inherit from a base class:

class A {
  constructor(){}
  age() { return 15; }
}

class B {
  constructor() {
    Object.getOwnPropertyNames(A.prototype).forEach(prop => {
      if (prop !== 'constructor') {
        this[prop] = A.prototype[prop];
      }
    });
  }
}

const b = new B();

console.log(b.age());
ic3b3rg
  • 14,063
  • 4
  • 25
  • 49
3

I would try implementing B as a Proxy.

class A {
    constructor(){}
    age() { return 15; }
}

const b = new Proxy(new A(), {
    get: function(object, property) {
        if (typeof object[property] === 'function') {
            return object.property();
        }
    }
    set: function(object, property) {}
}

You can read into it more at MDN.

Morgan Wilde
  • 16,113
  • 9
  • 50
  • 97