tritims
tritims

Reputation: 52

Referencing one object function from another function within the same object

Is there any way to get something like the following to work in JavaScript?

function a (){


  return{
    x: function foo(){
      ......
    }

    y: function bar(){
      .......
      .......
      foo()    //Doesn't work
      .....
    }
  }
}

Is there a way to reference foo() inside the function bar() both of which happen to be inside the same return block?

Upvotes: 1

Views: 127

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075895

If bar will always/only be called as part of an expression looking it up on the object or in any other way that ensures this refers to the object during the call, e.g.:

theObject.y(); // Since you've called the property `y`

or

var b = theObject.y.bind(theObject);
b();

then you can use this.x() within bar to run foo (since you've used x rather than foo for the proprty name):

function a() {
  return {
    x: function foo(){
      console.log("I'm foo");
    },

    y: function bar(){
      console.log("I'm bar, calling foo");
      this.x();
    }
  };
}

var obj = a();
obj.y();

When you do that, this will refer to the object within foo as well, which is handy if you need to refer to other object properties.


If bar may be called a different way, then you probably want to define the functions separately and then combine them in an object:

function a() {
  function foo(){
    // ......
  }

  function bar(){
    // .......
    // .......
    foo();
    // .....
  }

  return { x: foo, y: bar };
}

Example:

function a() {
  function foo(){
    console.log("I'm foo");
  }

  function bar(){
    console.log("I'm bar, about to call foo");
    foo();
  }

  return { x: foo, y: bar };
}

var obj = a();
obj.y();

When foo is called this way, this will be undefined (in strict mode) or a reference to the global object (in loose mode), not a reference to the object; if you need a reference to the object, there are various ways to do that, such as assigning it to a variable that both foo and bar close over.

Upvotes: 1

Related Questions