jQuery/javascript包装代码查询

Cal*_*tor 1 javascript jquery

我继承了一些以下列方式包装的javascript代码:

(function ($) {
    //some javascript using jQuery here...               
} (jQuery));
Run Code Online (Sandbox Code Playgroud)

它有什么作用?

use*_*716 5

它立即调用一个匿名函数,将全局jQuery作为参数传递给函数调用,然后由$参数引用.

这可以确保该$函数是本地函数,因此如果其他库正在使用全局$标识符,则不会发生冲突.

可以这样想:

   // create a function that receives jQuery as an argument
function keepItLocal( $ ) {

    // execute your jQuery code in here
    //   where $ is now a reference to jQuery     

};

   // invoke the function, passing in the global jQuery
keepItLocal( jQuery );
Run Code Online (Sandbox Code Playgroud)

因为在JavaScript中对变量进行范围限定的唯一方法是在函数中,这是防止全局命名空间污染的常见模式.

如果我们这样做:

$ = jQuery;

$('.someClass').someMethod();
Run Code Online (Sandbox Code Playgroud)

... $如果先前已定义,我们可能会覆盖,或者某些其他代码可能会出现并覆盖它.