0

I was writing a global javascript function. And after some mistakes (and a few searches here) I got it to work. But I also saw an example with (function($){ code here }(jQuery);

what is the difference (if any) and is there any advantage between option 1 and 2? both perform my task well. I am just trying to learn the difference.

OPTION #1

(function($){ TEAM={ getQB: function( success, failure) { var user=USER.user_data.login.toUpperCase(); $.ajax({ type: "GET", url: "/nfl/getQB?username="+user, dataType: 'json', async: false, success: success, error: failure, timeout: 6000 }); }, getRB: function( success, failure ) { userx=USER.user_data.login.toUpperCase(); $.ajax({ type: "GET", url: "/nfl/getRB?username="+userx, dataType: 'json', async: false, success: success, error: failure, timeout: 6000 }); } } })(jQuery); 

OPTION #2

 var TEAM={ getQB: function( success, failure) { var user=USER.user_data.login.toUpperCase(); $.ajax({ type: "GET", url: "/nfl/getQB?username="+user, dataType: 'json', async: false, success: success, error: failure, timeout: 6000 }); }, getRB: function( success, failure ) { userx=USER.user_data.login.toUpperCase(); $.ajax({ type: "GET", url: "/nfl/getRB?username="+userx, dataType: 'json', async: false, success: success, error: failure, timeout: 6000 }); } } 
2

2 Answers 2

2

Option 1

(function($){ code here })(jQuery) is an immediately-invoked function expression. It provides a temporary scope for variables declared within it. So in this instance, you're passing in a reference to JQuery that will be accessed by $ just within that block of code.

jQuery.noConflict(); //Remove assignment to $ (function($){ console.log($); //jQuery function })(jQuery) console.log($); //undefined console.log(jQuery); //jQuery function 

Option 2

If your code isn't within a function scope, it attaches TEAM to the window object. This pollutes the global namespace and couple potentially cause problems down the road. Imagine if someone made another object/function with the same name in the global. Depending on your code, your TEAM can be overwritten.

Option 1 is then preferred so you can avoid namespace collisions.

Sign up to request clarification or add additional context in comments.

3 Comments

Note: to get jQuery to give up being assigned to $ you have to call jQuery.noConflict(). Otherwise exactly correct!
Thanks, Alex! I forgot that the assignment was automatic.
awesome thanks a million! Now i see why other people did option 1.
0

In the first option you are sure that you use jQuery, because you are passing it as a parameter of the closure. In the second option you may have something else which stands behind $.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.