!function($){}(window.jQuery)是什么意思.
求详细解释。

JavaScript code 就是返回值取反,等价(function(){})()匿名函数直接执行了,只是用取反的标志可以活力匿名函数左右的括号!!?
1
2
3
4
5
<script type= "text/javascript" >
     ! function ($){
         //一些代码
     }(window.jQuery)
</script>

谢谢,做个记录
http://www.jcodecraeer.com/a/jquery_js_ajaxjishu/2012/0628/290.html
http://stackoverflow.com/questions/10896749/what-does-function-function-window-jquery-do?rq=1
就是返回值取反,等价(function(){})()匿名函数直接执行了,只是用取反的标志可以活力匿名函数左右的括号!!

Lets explain by Breaking up the code

function () {}()

Or often written as

(function () {})()

Is a self-invoking anonymous function, also known as Immediately-Invoked Func­tion Expres­sions (IIFEs). Which executes the anonymous function inline immediately.

Read more about this at Explain JavaScript's encapsulated anonymous function syntax.

Anonymous functions are a powerful feature and have benefits like scoping ("variable name spacing"), see What is the purpose of a self executing function in javascript?.


Now they are using

function ($) {}(window.jQuery)

Let's skip the ! for now.

So they are passing, window.jQuery into that function as argument and accepting as $.

What this does is making $ an alias to window.jQuery (original jQuery Object) and hence ensuring that the $ will always refer to the jQuery object inside that closure, no matter if other library has taken that($) outside.

So code you write inside that closure using $ will always work.

Another benefit is that $ comes as an argument in the anonymous function, which brings it closer in the scope chain and hence it takes less time for the JS interpreter to find the $ object inside the closure than it would otherwise took if we used the global $.


$(function(){  })

It's jQuery's document ready block as you might already know, which ensures that code inside this function will run when dom is ready, and hence all event binding's will work properly.

Read more at http://api.jquery.com/ready/

And what that ! does has been well explained here or at What does the exclamation mark do before the function?

In Short:

To demonstrate the benefits of !, Lets consider a case,

(function() {alert('first');
}())(function() {alert('second');
}())

If you paste the above code in console, you will get two alerts, but then you will get this error

TypeError: undefined is not a function

Why this happens? Let's simulate how JS engines executes the above code block. It executes this anonymous function function() {alert('first');}() shows the alert and as it returns nothing undefined is returned inside the (). Same happens for the second function too. So after the execution of this block, it ends up having something like

(undefined)(undefined)

and as it's syntax is like a self-invoking anonymous function, it tries to call that function, but the first,(undefined) is not a function. So you get undefined is not a function error. ! fixes this kind or errors. What happens with !. I am quoting the lines from the above answer link.

When you use !, the function becomes the single operand of the unary (logical) NOT operator.

This forces the function to be evaluated as an expression, which allows it to be invoked immediately inline.

and this solves the above problem, we can rewrite the above block using ! like

!(function() {alert('first');
}())!(function() {alert('second');
}())

For your case you can simply put your tooltip code inside a document ready block like this

$(function(){  $("[rel=tooltip]").tooltip();
});

and it will work fine.

And if you just use $("[rel=tooltip]").tooltip() without any doc ready block, then there is a chance when this code will run, there isn't any element with rel=tooltip in DOM yet. So $("[rel=tooltip]") will return an empty set and tooltip won't work.

An example markup when it won't work without doc ready block,

.
.
.
<script type="text/javascript">$("[rel=tooltip]").tooltip();
</script>
.
.
.
.
<a href="#" rel="tooltip">Something</a>
<a href="#" rel="tooltip">Something</a>
<a href="#" rel="tooltip">Something</a>

As browsers, interprets the markup sequentially, it will execute the js code as soon as it face it as. And when it executes the JS block here, it hasn't yet parsed the a rel="tooltip" tags yet, as it appears after the JS block, So they are not in DOM at that moment.

So for the above case $("[rel=tooltip]") is empty and hence tooltip won't work. So it's always safe to put all your JS code inside document ready block like

$(function){// put all your JS code here
});

Hope all this makes sense to you now.

其它的。

摘要 函数 是JavaScript中最灵活的一种对象,这里只是讲解其匿名函数的用途。匿名函数:就是没有函数名的函数。 函数的定义,大致可分为三种方式: 第一种:这也是最常规的一种 function double(x){ return 2 * x; } 第二种:这种方法使用了Function构造函数,把

函数是JavaScript中最灵活的一种对象,这里只是讲解其匿名函数的用途。匿名函数:就是没有函数名的函数。

函数的定义,大致可分为三种方式:

第一种:这也是最常规的一种

1
2
3
function double(x){   
     return 2 * x;      
}

第二种:这种方法使用了Function构造函数,把参数列表和函数体都作为字符串,很不方便,不建议使用。

1
var double = new Function( 'x' , 'return 2 * x;' );

第三种:

1
var double = function (x) { return 2* x; }

注意“=”右边的函数就是一个匿名函数,创造完毕函数后,又将该函数赋给了变量square。

匿名函数的创建

第一种方式:就是上面所讲的定义square函数,这也是最常用的方式之一。

第二种方式:

1
2
3
( function (x, y){  
     alert(x + y);    
})(2, 3);

这里创建了一个匿名函数(在第一个括号内),第二个括号用于调用该匿名函数,并传入参数。括号是表达式,是表达式就有返回值,所以可以在后面加一对括号让它们执行.

自执行的匿名函数

1. 什么是自执行的匿名函数?
    它是指形如这样的函数: (function {// code})();

2. 疑问
    为什么(function {// code})();可以被执行, 而function {// code}();却会报错?

3. 分析
    (1). 首先, 要清楚两者的区别:
    (function {// code})是表达式, function {// code}是函数声明.
    (2). 其次, js"预编译"的特点:
    js在"预编译"阶段, 会解释函数声明, 但却会忽略表式.
    (3). 当js执行到function() {//code}();时, 由于function() {//code}在"预编译"阶段已经被解释过, js会跳过function(){//code}, 试图去执行();, 故会报错;
    当js执行到(function {// code})();时, 由于(function {// code})是表达式, js会去对它求解得到返回值, 由于返回值是一 个函数, 故而遇到();时, 便会被执行.

另外, 函数转换为表达式的方法并不一定要靠分组操作符(),我们还可以用void操作符,~操作符,!操作符……

如:

1
2
3
! function (){  
   alert( "另类的匿名函数自执行" );  
}();

匿名函数与闭包

闭包的英文单词是closure,这是JavaScript中非常重要的一部分知识,因为使用闭包可以大大减少我们的代码量,使我们的代码看上去更加清晰等等,总之功能十分强大。

闭包的含义:闭包说白了就是函数的嵌套,内层的函数可以使用外层函数的所有变量,即使外层函数已经执行完毕(这点涉及JavaScript作用域链)。

1
2
3
4
5
6
7
function checkClosure(){ 
     var str = 'rain-man'
     setTimeout( 
         function (){ alert(str); } //这是一个匿名函数 
     , 2000); 
checkClosure();

这个例子看上去十分的简单,仔细分析下它的执行过程还是有许多知识点的:checkClosure函数的执行是瞬间的(也许用时只是0.00001毫秒),在checkClosure的函数体内创建了一个变量str,在checkClosure执行完毕之后str并没有被释放,这是因为setTimeout内的匿名函数存在这对str的引用。待到2秒后函数体内的匿名函数被执行完毕,str才被释放。

用闭包来优化代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function forTimeout(x, y){ 
     alert(x + y); 
function delay(x , y  , time){ 
     setTimeout( 'forTimeout(' +  x + ',' +  y + ')' , time);     
/** 
  * 上面的delay函数十分难以阅读,也不容易编写,但如果使用闭包就可以让代码更加清晰 
  * function delay(x , y , time){ 
  *     setTimeout( 
  *         function(){ 
  *             forTimeout(x , y)  
  *         }           
  *     , time);    
  * } 
  */

匿名函数最大的用途是创建闭包(这是JavaScript语言的特性之一),并且还可以构建命名空间,以减少全局变量的使用。

1
2
3
4
5
6
7
8
var oEvent = {}; 
( function (){  
     var addEvent = function (){ /*代码的实现省略了*/ }; 
     function removeEvent(){} 
     
     oEvent.addEvent = addEvent; 
     oEvent.removeEvent = removeEvent; 
})();

在这段代码中函数addEvent和removeEvent都是局部变量,但我们可以通过全局变量oEvent使用它,这就大大减少了全局变量的使用,增强了网页的安全性。 我们要想使用此段代码:oEvent.addEvent(document.getElementById('box') , 'click' , function(){});

1
2
3
4
5
6
7
8
var rainman = ( function (x , y){ 
     return x + y; 
})(2 , 3); 
/** 
  * 也可以写成下面的形式,因为第一个括号只是帮助我们阅读,但是不推荐使用下面这种书写格式。 
  * var rainman = function (x , y){ 
  *    return x + y; 
  * }(2 , 3);

在这里我们创建了一个变量rainman,并通过直接调用匿名函数初始化为5,这种小技巧有时十分实用。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var outer = null
     
( function (){ 
     var one = 1; 
     function inner (){ 
         one += 1; 
         alert(one); 
    
     outer = inner; 
})(); 
     
outer();    //2 
outer();    //3 
outer();    //4

这段代码中的变量one是一个局部变量(因为它被定义在一个函数之内),因此外部是不可以访问的。但是这里我们创建了inner函数,inner函数是可以访问变量one的;又将全局变量outer引用了inner,所以三次调用outer会弹出递增的结果。

注意

1 闭包允许内层函数引用父函数中的变量,但是该变量是最终值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/** 
  * <body> 
  * <ul> 
  *     <li>one</li> 
  *     <li>two</li> 
  *     <li>three</li> 
  *     <li>one</li> 
  * </ul> 
  */
     
var lists = document.getElementsByTagName( 'li' ); 
for ( var i = 0 , len = lists.length ; i < len ; i++){ 
     lists[ i ].onmouseover = function (){ 
         alert(i);     
     }; 
}

你会发现当鼠标移过每一个<li>元素时,总是弹出4,而不是我们期待的元素下标。这是为什么呢?注意事项里已经讲了(最终值)。显然这种解释过于简单,当mouseover事件调用监听函数时,首先在匿名函数( function(){ alert(i); })内部查找是否定义了 i,结果是没有定义;因此它会向上查找,查找结果是已经定义了,并且i的值是4(循环后的i值);所以,最终每次弹出的都是4。

解决方法一:

1
2
3
4
5
6
7
8
var lists = document.getElementsByTagName( 'li' ); 
for ( var i = 0 , len = lists.length ; i < len ; i++){ 
     ( function (index){ 
         lists[ index ].onmouseover = function (){ 
             alert(index);     
         };                     
     })(i); 
}

解决方法二:

1
2
3
4
5
6
7
var lists = document.getElementsByTagName( 'li' ); 
for ( var i = 0, len = lists.length; i < len; i++){ 
     lists[ i ].$$index = i;    //通过在Dom元素上绑定$$index属性记录下标 
     lists[ i ].onmouseover = function (){ 
         alert( this .$$index);     
     }; 
}

解决方法三:

1
2
3
4
5
6
7
8
9
function eventListener(list, index){ 
     list.onmouseover = function (){ 
         alert(index); 
     }; 
var lists = document.getElementsByTagName( 'li' ); 
for ( var i = 0 , len = lists.length ; i < len ; i++){ 
     eventListener(lists[ i ] , i); 
}

2 内存泄露

使用闭包十分容易造成浏览器的内存泄露,严重情况下会是浏览器挂死


参考网址:  http://bbs.csdn.net/topics/390344894

本文地址:  http://blog.csdn.net/aerchi/article/details/47045119

!function($){}(window.jQuery) 是什么意思相关推荐

  1. jquery的2.0.3版本源码系列(2):21行-94行定义了一些变量和函数 jQuery=function(){}

    2.1.bug通过索引查询 这里的#13335是bug的索引,如何查询呢? 第一步,浏览器地址栏输入"https://bugs.jquery.com/". 第二步,在网页的搜索框里 ...

  2. jQuery入门基础-附案例

    文章目录 预备知识与后续知识及项目案例 为什么要学jquery jQuery介绍 JavaScript 库 jQuery的概念 jQuery的优点 体验jquery的使用 jquery到底是什么 jq ...

  3. jquery 1.7.2源码解析(二)构造jquery对象

    构造jquery对象 jQuery对象是一个类数组对象. 一)构造函数jQuery() 构造函数的7种用法: 1.jQuery(selector [, context ]) 传入字符串参数:检查该字符 ...

  4. 7 个 jQuery 最佳实践

    背景 在这篇文章中,我会给大家介绍在编写.调试和审查JavaScript代码的时候一些好的实践(至少我是这么认为的).事实上,我选择了其中7个最常见的场景. 1.使用CDN及其回退地址(fallbac ...

  5. 从jQuery的缓存到事件监听

    很久以前,我还在cnblogs里面逛的时候就提出过一个问题(刚找了半天没找到).不知道大家有没有发现,用jQuery选择器"选择"之后的DOM上会添加jQuery********* ...

  6. 使用谷歌jquery库文件的理由

    使用谷歌jquery库文件的理由 最近看到,那些引用jquery的文件那些网站,好多是使用谷歌的库:像这样的<script type="text/javascript"src ...

  7. vue中引入jquery报错问题

    vue-cli搭建的vue项目中使用到jquery插件,需要引入jquery, 在无任何配置的情况下,直接在组件中import引入,在mounted时候打印$ 会显示undefined报错问题, 感觉 ...

  8. jQuery.fn和jQuery.prototype区别。

    近期在读jQuery的源码. 发现这里有个东西很难理解. 这里的 jQuery , jQuery.fn , jQuery,fn,init ,jQuery,prototype 都代表什么. 来看下jQu ...

  9. jQuery 技术揭秘

    1.平时jquery调用页: index.html : <!DOCTYPE html> <html lang="en"> <head><m ...

最新文章

  1. ui设计师要懂哪些B端设计原则?
  2. 不要再封装各种Util工具类了,这个神级框架值得拥有!
  3. Node.js静态文件服务器实战[转]
  4. 可变数组集合ArrayList
  5. 如何从Windows远程上传文件到Linux(例如CentOS 7)
  6. PortraitFCN算法详解
  7. knn k的选取_KNN - 初窥K近邻算法
  8. python去噪音_python中的噪声是什么意思
  9. Android之jni深入
  10. js与flash结合使用
  11. 怎么用计算机弹是你,抖音带你去旅行怎么用计算器弹奏_抖音带你去旅行计算器乐谱_管理资源吧...
  12. 算法导论5.1 雇用问题
  13. 关于Universal-Image-Loader加载同一张图只成功一张的问题
  14. Redis设计与实现-集群
  15. 01.FFmpeg下载以及安装
  16. 省钱兄同城跑腿小程序源码uniapp前端模版源码(小程序+APP+H5)
  17. 全新整理:微软、谷歌、百度等公司经典面试100题[第1-60题]
  18. 杂谈:倘若flash支持JPEG XR格式?
  19. 华清远见22071作业1011
  20. 回顾小米公司的成功过程,用五个层次的问题阐述,小米的成功基础、小米的爆品特点、小米生态链模式的根本原因。

热门文章

  1. 信用有多重要?欠款200元,多付4万利息!(附逾期补救办法)
  2. Inventor文件中保存自定义数据 - 2
  3. 小米路由青春虚拟服务器,小米路由青春版刷padavan
  4. 百度关键字SEO排名优化方案与流程
  5. 哪些手机写作软件比较好用?3款优秀的手机写作软件让笔者更舒心
  6. POJ - 3628 Bookshelf 2
  7. windows命令之tcping安装和使用
  8. 每天一篇Makefile(二)
  9. 数据库同步非常实用的工具,阿里数据迁移工具yugong使用细则
  10. Android开发之在APP中打开ppt