【问题标题】:How to create an object who have alias for many others object's functions如何创建一个具有许多其他对象功能别名的对象
【发布时间】:2014-05-12 10:24:11
【问题描述】:

我这里有个情况。 举个例子:

function ScrewDriver(){
    var data = ...;
    this.driving = function(){
        //Some Stuff Here
    }
}

function Hammer(){
    var data = ...;
    this.stomp = function(){
        //Some Stuff Here
    }
}

function MultiTools(){
    this.screwDriver = new ScrewDriver();
    this.hammer = new Hammer();
}

这是我们示例的基础。 现在我想从 multiTools 但动态重定向工具功能。 让我们自己解释一下:

function Work(){
    this.tools = new MultiTools();
    this.tools.screw(); // I want to user directly the function of the proper object
    this.tools.hammer.stomp(); // Not like this;
}

我在想这样的事情:

function MultiTools(){
    this.screwDriver = new ScrewDriver();
    this.hammer = new Hammer();
    for(var prop in this.screwDriver){
        this[prop] = this.screwDriver[prop];
    }
    //Same for each object
}

但它并没有像我想要的那样工作,因为如果我在子对象函数中访问子对象数据,我会得到一个错误。 当我调用 this.tools.screw();我实际上想要 this.tools.screwDriver.screw(); 最后,我只想要一个重定向。

有人知道怎么做吗?

提前致谢。

【问题讨论】:

    标签: javascript object prototype multiple-inheritance


    【解决方案1】:

    你可以使用.bind():

       this[prop] = this.screwDriver[prop].bind(this.screwDriver);
    

    这可确保在调用函数时,它们将具有正确的 this 值。

    您可以为您的 MultiTools 对象编写一个通用函数:

    function MultiTools() {
      var multitool = this;
      function promoteMethods(subobj) {
        for (var prop in subobj)
          if (typeof subobj[prop] == 'function')
            multitool[prop] = subobj[prop].bind(subobj);
          else
            multitool[prop] = subobj[prop];
      }
    
      promoteMethods(this.hammer = new Hammer());
      promoteMethods(this.screwDriver = new ScrewDriver());
      // ...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-02-24
      • 1970-01-01
      • 2020-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-15
      相关资源
      最近更新 更多