1

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?

xxfast
  • 697
  • 5
  • 14
  • 1
    `Object.assign(this, myComponent)` – 4castle Mar 10 '17 at 07:49
  • @4castle this only copy over the object's properties, not any methods – xxfast Mar 10 '17 at 07:53
  • 1
    It is possible to copy over the methods, but [as seen here](http://stackoverflow.com/questions/30689817/es6-call-class-constructor-without-new-keyword) you can't invoke `Component`'s constructor on an arbitrary object, so ES6 classes may throw up some hurdles in your attempt to do this. – JLRishe Mar 10 '17 at 08:12

1 Answers1

0

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;
}
xxfast
  • 697
  • 5
  • 14