Jeff
Jeff

Reputation: 33

How can I access the innermost function of several nested functions?

I can't seem to get the right syntax for this. I know how to access the function 1 level deep, but 2 levels isn't working for me.

var firstFn = (function() {
  var secondFn = (function() {
    function inner() {
      return "hi";
    }

    return {
      inner: function() {
        return inner();
      }
    }

  })();

  return {
    secondFn: function() {
      return secondFn();
    }
  };
})();

console.log(firstFn.secondFn.inner());

Upvotes: 3

Views: 331

Answers (1)

thefourtheye
thefourtheye

Reputation: 239693

The secondFn is actually a function object. So, you need to invoke it like this

console.log(firstFn.secondFn().inner());

Note: Your inner secondFn() returns an object, not a function. So, you need to change it like this

return {
  secondFn: function() {
    return secondFn;       // Note the absence of `()`
  }
};

Note: I strongly recommend using different names for your functions and objects, like this. So that it would be less confusing to understand what is happening.

var firstFn = (function() {
  var innerSecond = (function() {

    function innerFunction() {
      return "hi";
    }

    return {
      inner: function() {
        return innerFunction();
      }
    }

  })();

  return {
    secondFn: function() {
      return innerSecond;
    }
  };

})();

So, firstFn is an object which has a property called secondFn, which is a function.

When the secondFn is called, it returns another object called innerSecond, which has a property called inner whose value is function.

When you invoke inner, it actually invokes innerFunction and returns the result hi.


If you wanted to follow the same pattern as in innerSecond, then you need to return the function object as it is, instead of invoking it, like this

var first = (function() {

  var innerSecondFunction = function() {

    function innerFunction() {
      return "hi";
    }

    return {
      inner: function() {
        return innerFunction();
      }
    }

  };    // Note that we don't invoke the function object here

  return {
    secondFn: function() {
      return innerSecondFunction();   // but we invoke here
    }

  };

})();

console.log(first.secondFn().inner());

Upvotes: 9

Related Questions