Home  >  Article  >  Web Front-end  >  jQuery中(function($){})(jQuery)详解_jquery

jQuery中(function($){})(jQuery)详解_jquery

WBOY
WBOYOriginal
2016-05-16 15:50:281036browse

Simply put

(function($){
 //code
})(jQuery)

Declares an anonymous function, that is, passes the jQuery object as a parameter to the function

Give me an example

// 全局
var str = "全局字符串...";
(function () { // 第1层
  (function () { // 第2层
    (function () { // 第3层
      (function () { // 第4层 层数越多,访问全局越慢
        console.time('全局');
        for (var i=0; i<1e6; i++) {
          str += Math.random().toString().substr(2, 2);
        }
        console.timeEnd('全局');
      })();
    })();
  })();
})();
 
// 局部
(function () { // 第1层
  (function () { // 第2层
    (function () { // 第3层
      (function () { // 第4层
        var str = "内部字符串...";
        var random = Math.random;
        console.time('内部');
        for (var i=0; i<1e6; i++) {
          str += random().toString().substr(2, 2);
        }
        console.timeEnd('内部');
      })();
    })()
  })();
})();

Run the code and you will see the effect. It is relatively slow, so please wait for a while.
I just tested and found that some computers with small memory can easily cause the browser to crash.
Chrome is so armed that even strings are cached, but it doesn’t have much effect.

It has nothing to do with speed, that’s what I think.

(function($){
// code
})(jQuery)

There are many jQuery plug-ins, and you cannot be sure that the variable or method name you use does not have the same name as other plug-ins, so you need to encapsulate all plug-in codes into an anonymous function;

Since the plug-in uses jQuery, you need to import jQuery into the anonymous function and use $ variable reference (because everyone is used to using $). Of course you can also use $ globally, but the first condition cannot be fulfilled;
The encapsulated code must be executed, so the anonymous function must be executed and jQuery parameters must be passed in.

Summary

In fact, it is to protect the $ symbol. No matter whether the outside world introduces another library that interferes with $, it will not interfere with the fact that $ in the anonymous function is jQuery, because he is passed in as a parameter.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn