1

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?

2
  • 1
    The optional name for a function expression is only available within the function itself (except for certain buggy versions of IE). Commented Jun 19, 2017 at 5:01
  • 1
    @ShubhamKhatri— the property name x is not mapped to a variable name x in a different function. Commented Jun 19, 2017 at 5:02

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.