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
  • 504
  • 6
  • 24

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,629
  • 4
  • 30
  • 53
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,795
  • 10
  • 53
  • 99