Javascript namespacing - how to export functions and variables defined in function scope based on their name?

In the code below, apart from specifying manually, is there a way to export only functions and variables whose name does not 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.}
}());

      

+3


source to share


1 answer


Your idea requires all variables to be in local scope. Unfortunately JavaScript is unable to do this. See this related question .

There are two ways I have seen this can be done:

1) Attach each variable when defined for the exported object:

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 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 have seen both (and even mixed of the two) that have been used in practice. The second one might sound more pedantic, but it also allows the reader to look at one segment of the code and see the entire interface returned by this function.

+5


source







All Articles