I’m creating some custom objects and functions which I want to hide from the global namespace (including restricting its accessibility).
If i place inside the document.ready function will it have the same effect as placing in a Closure or do i need to alias the jquery reference in the document.ready declaration to ensure my custom code stays out of the global namespace?
Option 1. Plain document ready
$(document).ready(function()
//do custom stuff
Option 2: Closure inside document ready
$(document).ready(function(){
(function($) {
//do custom stuff
})(jQuery);
Option 3: Alias the jquery reference in document ready
jquery(document).ready(function($) {
//do custom stuff
What would be the preferred option? Thanks
If you declare variables inside any function, they will be visible only in that function.
Also, to make sure that you have the correct
$in your scope, I would go for option 3 (but correct the function name fromjquerytojQuery). Options 1 and 2 already assume that$is the correct alias but option 3 will work even if$in the outer scope is not the same asjQuery(for example ifjQuery.noConflict()was called, or another library was loaded like Prototype.js etc) but makes the$always meanjQueryin your inner scope where you//do custom stuff.