cdugga
cdugga

Reputation: 3859

Jquery - namespaces and closures

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

Upvotes: 1

Views: 276

Answers (3)

lgomezma
lgomezma

Reputation: 1637

In JavaScript every function has its own scope, any object or variable that you declare inside of a function will only be seen by the function itself or other functions declared inside it.

The most common way to create a namespace is to create a function that is called automatically after its definition and that returns an object that will contain the data, like in your second option. Then all the data can be accessed through that object. In any case if you just want to hide variables from other parts of the code, just create a function and declare everything you want to hide in it.

Upvotes: 1

rsp
rsp

Reputation: 111434

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 from jquery to jQuery). 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 as jQuery (for example if jQuery.noConflict() was called, or another library was loaded like Prototype.js etc) but makes the $ always mean jQuery in your inner scope where you //do custom stuff.

Upvotes: 2

jAndy
jAndy

Reputation: 236102

You have to understand that every function in ECMAscript effectively is a closure. So, it doesn't really make any difference in your particular snippets, in which function(-context) you create those variables (beside accessibility from other contexts).

Upvotes: 3

Related Questions