Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

self executing function jquery vs javascript difference

What are the difference among -

First :-

(function () {      var Book = 'hello';  }()); 

Second:-

(function () {      var Book = 'hello';  })(); 

First and second are similar some how in work..

Third :-

(function ($) {      var Book = 'hello';  })(jQuery); 

What pattern I need to use and where in my coding.. Third module pattern I have seen while I was reading a article related to backboneJS.

What I understood from Third one "self executing function with the argument “jQuery”" ....

Can any please give me some idea about Immediately Invoked Function Expressions (IIFE).

Thanks !!

like image 944
Javascript Coder Avatar asked Oct 21 '13 10:10

Javascript Coder


2 Answers

In all cases you are doing an anonymous function. I think 1 is the same as 2. In the third case you are passing jQuery as an argument. This is done when you want to encapsulate jQuery within your function's scope.

For instance, in your application, jQuery var could be jQuery. But within your anonymous function you may want to use it as $.

(function ($) {     //Here jQuery is $     var Book = $(document.body).text();      })(jQuery);  //Out of your function, you user jQuery as jQuery (in this example) var Book = jQuery(document.body).text(); 
like image 65
Jorgeblom Avatar answered Sep 22 '22 21:09

Jorgeblom


This is called a closure to avoid conflicts with other libraries such as mootools which are using $. This way you can ensure to use $ in that function with passing jQuery as a param.

(function ($) {    $(function () { // Here in this block you can use '$' in place of jQuery     .......    }); })(jQuery); //<----passing jquery to avoid any conflict with other libraries. 
like image 27
Jai Avatar answered Sep 24 '22 21:09

Jai