With the code below, other than specifying manually, is there a way to export only the functions and variables whose name doesn’t start with an underscore?
var myapp = myapp || {};
myapp.utils = (function() {
var
CONSTANT_A = "FOO",
CONSTANT_B = "BAR";
function func() {}
function _privateFunc() {}
return {//return all variables and functions whose name does not have the "_" prefix.}
}());
Your idea requires being able to list all of the variables in the local scope. Unfortunately, JavaScript is not capable of doing that. See this related question.
There are two ways I’ve seen this be done:
1) Attach every variable when they’re defined to an object to be exported:
2) Or list all the exports at the end in an object literal:
I’ve seen both (and even mixes of the two) used in practice. The second may seem more pedantic, but also allows a reader to look at a single segment of code and see the entire interface returned by that function.