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:
var myapp = myapp || {};
myapp.utils = (function () {
var exports = {};
exports.CONSTANT_A = "FOO",
exports.CONSTANT_B = "BAR";
exports.func = function func() {}
function _privateFunc() {}
return exports;
}());
2) Or list all the exports at the end in an object literal:
var myapp = myapp || {};
myapp.utils = (function () {
var
CONSTANT_A = "FOO",
CONSTANT_B = "BAR";
function func() {}
function _privateFunc() {}
return {
CONSTANT_A: CONSTANT_A,
CONSTANT_B: CONSTANT_B,
func: func
};
}());
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.