2
 function1().function2();

How to Define a function to invoke like this?

  • 1
    Possible duplicate of [how does jquery chaining work?](https://stackoverflow.com/questions/7475336/how-does-jquery-chaining-work) –  May 11 '18 at 01:06

3 Answers3

4

In addition to the other answers, you usually would do this when coding a fluent interface, where you are returning the parent object to allow method chaining, which you could do like so:

var calculator = (function() {
      var i = 0;
      var public = {};
      public.add = function(a) { i += a; return public; }
      public.sub = function(a) { i -= a; return public; }
      public.equals = function() { return i; }
      return public;
})();
    
console.log(calculator.add(2).sub(3).add(20).equals());
dave
  • 62,300
  • 5
  • 72
  • 93
3

You'll need function1 to return an object that has a property of function2. For example:

function f1() {
  return {
    f2() {
      console.log('foo');
    }
  };
}
f1().f2();
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
3

here you have a working example, you can call function1 and get the object mapping to the functions that you desire.

function function1() {
  return {
    function2: f2
  }
}

function f2() {
  return "do something";
}

console.log(function1().function2())
Prince Hernandez
  • 3,623
  • 1
  • 10
  • 19