Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the (function() {})() construct work and why do people use it?

Tags:

javascript

(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

like image 355
Tom Lehman Avatar asked Oct 28 '09 18:10

Tom Lehman


People also ask

Why do we use functions in JavaScript?

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.

What does the this function do?

“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.

How does this keyword work?

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.


2 Answers

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.

like image 147
Seb Avatar answered Oct 09 '22 20:10

Seb


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 })(); 
like image 45
Daniel LeCheminant Avatar answered Oct 09 '22 18:10

Daniel LeCheminant