It is generally accepted that Javascript code should be wrapped in a function to prevent leaking to the global scope and just assign whatever you need outside of each function to the head object (window in web browsers).
I’ve seen two primary methods of this in the wild:
Method 1:
(function() {
// code here
}).call(this);
Method 2:
(function() {
// code here
})();
Method 1 is from compiled CoffeeScript code, and Method 2 seems to be the preferred style for jQuery plugins:
Modified Method 2 for jQuery:
(function($) {
// JQuery Code
})(jQuery);
Question: What is the difference between Method 1 and Method 2? CoffeeScript likes to focus on conciseness, so I figure there must have been a reason for the people behind CoffeeScript to choose Method 2 over Method 1.
They are very different.
Method 1 using call, allows you the change what
thisis inside the function. For example:Be careful though as you can still dump stuff on the global scope with both approaches: