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?
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With