什么(function($){...})(jQuery); 做?

use*_*212 -1 javascript cookies jquery

有人可以解释一下这段代码的作用是什么吗?

(function($) {
    $.cookie = function(key, value, options) {
         // Body of the function here
    }
})(jQuery);
Run Code Online (Sandbox Code Playgroud)

只是以这种方式宣布是不是更简单?

function cookie(key, value, options) {
     // Body of the function here
}
Run Code Online (Sandbox Code Playgroud)

Jai*_*Jai 6

这称为闭包,以避免与正在使用的其他库冲突$.这样,您可以确保$在该函数中使用jQuery作为参数传递.

(function ($) {
   $(function () {
    .......
   });
})(jQuery); //<----passing jquery to avoid any conflict with other libraries.
Run Code Online (Sandbox Code Playgroud)

Mootools,原型等库也使用$,这个闭包用于避免任何冲突.

  • 那个封闭太多了.更好地使用`jQuery(function($){...});` (2认同)

Dav*_*und 5

您正在创建一个接受 的匿名函数$,并立即调用它,传递jQuery. 这会创建一个闭包 where $is jQuery。也就是说,如果您知道jQuery在执行时这$将是一个 jQuery 实例,那么您也知道这将是该闭包中的一个 jQuery 实例实例。它是针对可能也定义$.