Dynamically attaching ES6 Object's methods from One object to another

70 views Asked by At

I have this basic component class that looks like this

class Component {
    constructor() {
        this.manager = null;
    }
    behavior(){
        //some behavior
    }
}

I want an instance of GameObject to dynamically inherit that behavior by doing something like

var myGameObject = new GameObject();
myGameObject.attach(myComponent);

so that I can easily do

myGameObject.behavior();

Is this possible through ES6? if not what other alternatives do I have?

1

There are 1 answers

0
xxfast On BEST ANSWER

I did found a way to do this, but not sure if this is just bad practice

attach(component){
   Object.assign(this,component);
   while (component = Reflect.getPrototypeOf(component)) {
     if(component == Object.prototype) break; // no need to redefine Object
     let keys = Reflect.ownKeys(component)
     for(var i=1;i<keys.length;i++){
       Reflect.getPrototypeOf(this)[keys[i]] = component[keys[i]];
     }
   }
   return this;
}