Javascript命名空间 - 如何根据命名导出函数范围内定义的函数和变量?

时间:2013-01-18 21:36:01

标签: javascript namespaces javascript-namespaces

使用下面的代码,除了手动指定外,有没有办法只导出名称不以下划线开头的函数和变量?

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.}
}());

1 个答案:

答案 0 :(得分:5)

您的想法要求能够列出本地范围内的所有变量。不幸的是,JavaScript无法做到这一点。请参阅this related question

我已经看到过两种方式:

1)将每个变量定义到要导出的对象时附加:

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)或者在对象文字中列出最后的所有导出:

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
    };
}());

我在实践中看到过两种(甚至是两种混合物)。第二个可能看起来更迂腐,但也允许读者查看单个代码段并查看该函数返回的整个界面。