(function() {})()
and its jQuery-specific cousin (function($) {})(jQuery)
pop up all the time in Javascript code.
How do these constructs work, and what problems do they solve?
Examples appreciated
JavaScript Functions. JavaScript provides functions similar to most of the scripting and programming languages. In JavaScript, a function allows you to define a block of code, give it a name and then execute it as many times as you want. A JavaScript function can be defined using function keyword.
“This” keyword refers to an object that is executing the current piece of code. It references the object that is executing the current function. If the function being referenced is a regular function, “this” references the global object.
In JavaScript, the this keyword refers to an object. Which object depends on how this is being invoked (used or called). The this keyword refers to different objects depending on how it is used: In an object method, this refers to the object.
With the increasing popularity of JavaScript frameworks, the $
sign was used in many different occasions. So, to alleviate possible clashes, you can use those constructs:
(function ($){ // Your code using $ here. })(jQuery);
Specifically, that's an anonymous function declaration which gets executed immediately passing the main jQuery object as parameter. Inside that function, you can use $
to refer to that object, without worrying about other frameworks being in scope as well.
This is a technique used to limit variable scope; it's the only way to prevent variables from polluting the global namespace.
var bar = 1; // bar is now part of the global namespace alert(bar); (function () { var foo = 1; // foo has function scope alert(foo); // code to be executed goes here })();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With