Javascript转换为命名空间和调用函数

时间:2011-08-12 10:21:10

标签: jquery javascript-namespaces

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

所以示例函数写成:

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

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

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

任何帮助都会很棒。

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分:1)

billy moon显示了一个良好的开端,但使用对象文字的问题在于,你无法交叉引用其他字段/函数/属性。

我更喜欢揭示模块模式(参见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!

我喜欢这个的一个原因是,通过浏览从自执行函数返回的对象文字,很容易看到什么是公共/私有

希望有用

相关问题