Pergunta

I have a situation here. Let's show an example:

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

Here is the base of our example. Now I would like redirect the tools functions from the multiTools but dynamicaly. Let's explain myself:

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

I was thinking of something like that:

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
}

But it's not working like I want because if I acces to the child object data in the child object function I'll get an error. When im calling this.tools.screw(); I want in reality this.tools.screwDriver.screw(); In finally I just want a redirection.

Someone know how to do this?

Thanks in advance.

Foi útil?

Solução

You can use .bind():

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

That ensures that when the functions are called, they'll have the correct value of this.

You could write a general function for your MultiTools object:

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());
  // ...
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top