4

it is possible to declare a function inside a function in javascript. Like:

function my(){
   function check(){
      return true;
   }

   console.log( check() ? "yes" : "no");
}

my();

However, it might not be the fastest because, everytime my is called, check must be declared anew. But declaring check outside of my would pollute the global scope.

If my was an constructor My, check could be added to its prototype, but unfortunately this does not work with normal functions.

What is the convenient way to solve this problem?

Anton Harald
  • 5,402
  • 2
  • 17
  • 45

2 Answers2

9

If you can really reuse check between calls to my, then you can create my and check within an inline-invoked scoping function and return my out of it:

var my = function() { // <=== Scoping function

    function my(){
        console.log( check() ? "yes" : "no");
    }

    function check(){
        return true;
    }

    return my;        // <=== Returns `my`
}();                  // <=== () calls scoping immediately

my();

Now, check is private, but not recreated every time you call my.

This is a simple example of the revealing module pattern. You hide most things in the scoping function, and "reveal" the things you want to publish out of it. If you have more than one thing to publish, you return an object with the things on it as properties.

Sometimes you see it written with parens around the scoping function, not because they're necessary (they aren't if you're using the return value), but because you'd need them (or something with a similar effect) if you weren't using the return value, and so it makes it more obvious that it's a scoping function:

var my = (function() { // <=== Scoping function

    function my(){
        console.log( check() ? "yes" : "no");
    }

    function check(){
        return true;
    }

    return my;         // <=== Returns `my`
})();                  // <=== () calls scoping immediately

my();
Community
  • 1
  • 1
T.J. Crowder
  • 879,024
  • 165
  • 1,615
  • 1,639
-1

Not sure if I understand your question correctly but you can set the function as part of the return, and call it only when you want to, something like:

function my(){
    // Function code here
    return {
        check : function(){
            return true;
        }
    };
}

var myVar = my();
console.log(myVar.check() ? "true" : "false");
Walter R
  • 403
  • 1
  • 6
  • 9