Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function Inside a JavaScript Function Without Declaring it Everytime Anew

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?

like image 679
Anton Harald Avatar asked Feb 09 '23 11:02

Anton Harald


1 Answers

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();
like image 100
T.J. Crowder Avatar answered Feb 11 '23 23:02

T.J. Crowder