1

我是一个典型的 Web 开发人员,在 JS 中的所有内容都使用全局。我现在已经看到了曙光并想转换为命名空间。因此,在我当前的项目中,我有一个页面,其中包含三个 JS 函数(当前都是全局函数),当调用这些函数时,将文本分配给锚点并附加点击方法来切换特定 div 的可见性。很标准。

所以一个示例函数写成:

function toggleComments(){
   $("comments-section").hide();
   $("comments-button").click(function (){
      blah
      return false;
   });
}

我的问题是如何创建一个命名空间来保存这些函数然后调用它们?

我找到了不同的例子,但没有任何结论。

任何帮助都会很棒。

4

2 回答 2

2
// choos a namespace name that will not conflict with existing global variables
var myNS = {
        toggleComments: function(){
            $("comments-section").hide();
            $("comments-button").click(function (){
                // blah
                return false;
            });
        },
        anotherFunc: function(){
            return "something";
        }
}

// called like this
myNS.toggleComments();
alert( myNS.anotherFunc() );

此外,您应该尝试将代码包含在匿名自调用函数中。这意味着您可以在全局命名空间中没有任何内容,因此没有污染风险。

// other peoples/modules code
var myVariable = "whatever";

// anonymous function for your self contained code
(function(){
var myVariable = "inside anonymous function";
alert(myVariable);
})() // the empty brackets envoke the anonymous function

// still retains value from before your self envoking anonymous function
alert(myVariable);
于 2011-08-12T10:27:26.693 回答
1

比利月亮显示了一个良好的开端,但使用对象文字的问题是您不能交叉引用其他字段/函数/属性。

我更喜欢显示模块模式(参见http://www.wait-till-i.com/2007/08/22/again-with-the-module-pattern-reveal-something-to-the-world/

揭示模块模式结合了一个自执行功能,利用(某种)闭包来提供内部私有函数/字段,并允许您传递参数来初始化您的命名空间对象。

var namespacedObject = function(param) {

    var settings = param || someDefaultSetting, //default if no param supplied
        somePrivateField = "someValue",
        somePublicField = "i'm public";

    //define some method we will later make public
    function toggleComments(){
        $("comments-section").hide();
        $("comments-button").click(function (){
             $(this).value= somePrivateField;
             return false;
        });
    }

    //this is where the magic happens, 
    //return object with all public fields/functions
    return { 
        toggleComments : toggleComments,
        somePublicField : somePublicField
    };

}(someParam);

您可以看到命名空间对象包含一个私有字段somePrivateField,可以从可公开访问的方法中引用。另外,请注意我已经公开了一个公共字段,并接受了一些我可以在函数等中使用/引用的参数(如果没有传入任何内容,您可以将其默认为某个默认值。

可以这样使用:

namespacedObject.toggleComments();
alert(namespacedObject.somePublicField);
alert(namespacedObject.somePrivateField); //undefined - it's private of course!

我喜欢这个的一个原因是,只要看一眼自执行函数返回的对象字面量,就很容易看出什么是公共/私有的

希望这会有所帮助

于 2011-08-12T11:11:10.150 回答