【问题标题】:Dynamically attaching ES6 Object's methods from One object to another将 ES6 对象的方法从一个对象动态附加到另一个对象
【发布时间】:2017-03-10 07:46:26
【问题描述】:

我有一个看起来像这样的基本组件类

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

我希望 GameObject 的实例通过执行类似的操作来动态继承该行为

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

这样我就可以轻松搞定

myGameObject.behavior();

这可以通过 ES6 实现吗?如果不是,我还有什么其他选择?

【问题讨论】:

  • Object.assign(this, myComponent)
  • @4castle 这个只复制对象的属性,而不是任何方法
  • 可以复制方法,但是as seen here 你不能在任意对象上调用Component 的构造函数,所以 ES6 类可能会在你尝试这样做时遇到一些障碍这个。

标签: javascript ecmascript-6 component-design


【解决方案1】:

我确实找到了一种方法来做到这一点,但不确定这是否只是不好的做法

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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多