Home > Web Front-end > JS Tutorial > body text

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

WBOY
Release: 2016-05-16 15:50:28
Original
1002 people have browsed it

简单的说

(function($){
 //code
})(jQuery)
Copy after login

声明了一个匿名函数,也就是将jQuery对象作为参数传给函数

给大家举个例子

// 全局
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('内部');
      })();
    })()
  })();
})();

Copy after login

运行代码 就可以看到效果了,比较慢,骚等片刻。
我刚刚测试发现一些内存小的电脑容易直接导致浏览器崩溃、
chrome武装到牙齿了,连字符串都缓存,看不出多大效果、

和速度应该没关系,我是这么认为的。

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

Copy after login

jQuery插件众多,你无法确定自己使用的变量或者方法名不于其他插件重名,所以需要将所有插件代码封装到一个匿名函数当中;

由于插件使用了jQuery所以需要导入jQuery到匿名函数中,同时使用$变量引用(因为大家已经习惯了使用$)。当然你在全局下也可以使用$,但是无法完成第一个条件;
封装的代码必须执行,所以要执行匿名函数同时传入jQuery参数。

总结

其实是为了保护$符号,不管外界是否引入了另外有干扰$的库,都不会干扰匿名函数中$就是jQuery的事实,因为他是作为参数被传进去的。

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!