!function($){}(window.jQuery) 是什么意思

!function($){}(window.jQuery)是什么意思.
求详细解释。
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 内存泄露

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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值