views:

34

answers:

2

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();
});
+3  A: 

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.

Matthew Flaschen
+2  A: 

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 $.

naikus