Why do some people write a function like $ (function ($)

I know that type code $(function( $ )does not make any sense, but I found such code in various places, including todomvc .

There is a reason to write functions such as jQuery(function( $ )to resolve any potential conflict $used by some other library, but not $function($).

+5
source share
10 answers

No reason to use

$(function($))...

If you use the dollar sign at the beginning of the line, you rely on the jQuery object, so if you pass the jQuery object later as a parameter to avoid conflicts, why didn't you use it in the first place? It's too late for this now ...

The correct way to use:

(function($){ // The dollar variable is a parameter.
   $(function(){ // You use the $ variable only inside the function.
   });
})(jQuery); // jQuery is passed as a parameter.

$.somePrototypeFunctionHere(); // Here the dollar variable can be something else.
+3

:

$(function($) {
});

, , $ (, ).

jQuery DOM ready, :

jQuery(function($) {
    // this === document
    // $ === jQuery
});

:

readyList.resolveWith( document, [ jQuery ] );

this document jQuery. , , , Deferred.

:

(function($) {
  $(function() {
  }
}(jQuery));

, , , .

+3

jQuery DOM, . :

$(document).ready(function(){});

:

$(function(){});

# 1: $() jQuery()!

jQuery vs. $, , $ . , MooTools Prototype JS. , , $ jQuery.

jQuery jQuery.noConflict();, jQuery $, $ jQuery. , .

Prototype.JS $ ; .

, $ Prototype. document.getElementById, () DOM node .


# 2: $ ...

:

$(function($){})

(function($){})(jQuery);

$(function(){});

, .:)

+2

, $(function(){}), , . .. jquery, . , .

+1
$(function( $ ) 

$(document).ready(function() {

: Jquery(function( $ ) jquery js-

+1

, , , $, jQuery , jQuery, $ lib.

jQuery

+1

$:

(function($){
   $(function(){
      // all the code stuff here....
   });
})(jQuery);

:
My question is actually misunderstood by many giving answers. I want to know about the dollar as an argument in the function.

$, jQuery, , $, .

:

jQuery IIFE (Expression Exited Function Expression), , ​​ .

(function($) {
     // all other things    
})(jQuery);

jQuery , .

,

0
$(function() { 
  // Do your code here...
}); 

, .

(function($){ 
  // Do your code here...
})(jQuery); 

$ , $.

, .

(function($){ 
   $(function() { 
      // Do your code here... 
   }); 
})(jQuery);
0

ready() | JQuery

jQuery

JavaScript $.noConflict(), . , $ , jQuery , $. , .ready(), , jQuery. , .ready(), :

jQuery(document).ready(function($) {
  // Code using $ as usual goes here.
});

, DOM. jQuery -

:

jQuery(document).ready(function($){})

jQuery().ready(function($){}) //(this is not recommended)

jQuery(function($){})

-

(function($) { /* some code that uses $ */ })(jQuery)

this.

0

Your question is not clear. Passing an object JQuerymakes it a local area (as far as I know, to the module). It is used as a performance enhancement.

(function($) {
  // Code in here
})(jQuery);
0
source

All Articles