0

Is it possible to call the function locally defined in another function in JavaScript? I have a code pretty much like this:

var module = function () {
    function inner() {
        // Some code here
    }
    // Some code here
}

var originalModule = module;
var module = function () {
    originalModule();
    // inner() must be called here
}

So I'm overriding the original module implementation, but at some point in the new implementation I need to call inner() function. I cannot edit the original implementation. So far the only way I see is to copy inner() function from original and define it in the new one. Is there another way?

jetpackpony
  • 1,270
  • 1
  • 12
  • 22
  • seems like very-very bad design. Why do you need to call it? If you need it outside the function, why declare it *inside* the function anyway? – The Paramagnetic Croissant Oct 22 '14 at 15:18
  • 2
    No, you can't reach into a variable scope from outside. That would defeat the purpose of scope. You could have the original module *return* the function, or make it accessible in some other way, but that's about it. –  Oct 22 '14 at 15:20

2 Answers2

1

As inner() is defined inside of module() scope, you can't access it outside of this scope..

This pattern is used to implement private methods of module().

Kate Miháliková
  • 2,035
  • 15
  • 21
0

It's usually not a good practice, but you could do something like this:

  function a(x) {    // <-- function
      function b(y) { // <-- inner function
        return x + y; // <-- use variables from outer scope
      }
      return b;       // <-- you can even return a function.
   }
   a(3)(4);           // == 7.
Community
  • 1
  • 1
Dany Caissy
  • 3,176
  • 15
  • 21