简体   繁体   English

JavaScript命名空间声明差异

[英]JavaScript Namespace Declaration Differences

What are the differences between these two types of namespace declarations? 这两种类型的名称空间声明之间有什么区别? Is the first one better than the second one or vice versa? 第一个比第二个更好吗?反之亦然?

(function($)
{
    $.build = {
        init: function()
        {
            this.attachEvents();
        }
    }
}

$(document).ready(function() {
        $.build.init();
    });
})(jQuery);

versus

var build = {
    init: function(){
        this.attachEvents();
    }
};

$(document).ready(function() {
        build.init();
});

There are two main practical differences. 实际存在两个主要区别。 The first creates no additional externally accessible variables, and doesn't depend on $ being jQuery outside the function. 第一个不创建其他外部可访问变量,并且不依赖$是函数外部的jQuery The second creates a build variable, and requires that $ mean jQuery . 第二个创建一个build变量,并要求$ mean jQuery

Both are good but the first one is probably better in that it allows jQuery to play safe with other libraries. 两者都很好,但是第一个可能更好,因为它允许jQuery与其他库一起安全地运行。 It does not collide with any other variables declared as $. 它不会与其他任何声明为$的变量发生冲突。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM