开发者

JavaScript Namespace Declaration Differences

开发者 https://www.devze.com 2023-01-11 16:49 出处:网络
What are the differences between th开发者_C百科ese two types of namespace declarations? Is the first one better than the second one or vice versa?

What are the differences between th开发者_C百科ese 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. The second creates a build variable, and requires that $ mean jQuery.


Both are good but the first one is probably better in that it allows jQuery to play safe with other libraries. It does not collide with any other variables declared as $.

0

精彩评论

暂无评论...
验证码 换一张
取 消