!function($){$(function(){})}(window.jQuery)是做什么的? [英] What does !function ($) { $(function(){ }) }(window.jQuery) do?

查看:124
本文介绍了!function($){$(function(){})}(window.jQuery)是做什么的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Twitter引导程序创建网站,并试图初始化工具提示.除了在application.js中添加类似的内容:

 $("[rel=tooltip]").tooltip()  

之外,除非保留,否则引导文档中将使用以下代码,我的工具提示不会初始化.

!function ($) {

  $(function(){  

  })

}(window.jQuery)

以上代码有什么作用?

解决方案

通过分解代码来说明

function () {
}()

或通常写为

(function () {
})()

self-invoking anonymous函数,也称为立即调用的函数表达式(IIFE).它将立即内联执行匿名函数.

请访问详细了解此内容,以解释封装的匿名函数语法.

匿名功能是一项强大的功能,并具有诸如范围界定(可变名称间距")之类的好处,请参见自我的目的是什么?用javascript执行功能?.


现在他们正在使用

function ($) {

}(window.jQuery)

现在暂时跳过!.

因此,他们将window.jQuery作为参数传递给该函数并接受为$.

这是使$成为window.jQuery(原始jQuery对象)的别名,因此确保$将始终引用该closure中的jQuery object,无论其他库是否具有将($)带到外面.

因此,您使用$在该闭包中编写的代码将始终有效.

另一个好处是$作为匿名函数中的参数来使用,这使它在scope chain中更紧密,因此JS解释器在闭包内部查找$对象所花费的时间少于它.如果我们使用全局$,则将花费其他时间.


$(function(){  

})

您可能已经知道,这是jQuery的文档就绪块,可确保该函数中的代码在dom is ready时运行,因此所有event binding's都将正常运行.

http://api.jquery.com/ready/

上了解更多信息.

!的操作已得到很好的解释,此处或在功能前使用感叹号做什么?

简而言之:

为演示!的好处,让我们考虑一个案例,

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


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

如果将上面的代码粘贴到console中,则会收到两个警报,但是会出现此错误

TypeError: undefined is not a function

为什么会这样?让我们模拟一下JS引擎如何执行上述代码块.它执行此匿名函数function() {alert('first');}()会显示警报,并且由于未返回任何内容,因此()内未返回undefined.第二个功能也是如此.因此,执行完此块后,它最终会出现类似

的内容

(undefined)(undefined)

的语法就像self-invoking anonymous函数一样,它会尝试调用该函数,但是第一个(undefined)不是函数.这样您会得到undefined is not a function错误. !修复了此类错误. !会发生什么.我引用了上面答案链接中的行.

当您使用!时,该函数将成为一元的单个操作数 (逻辑)非运算符.

这强制将函数评估为表达式,其中 允许立即内联调用它.

这解决了上面的问题,我们可以像

!function ($) {

  $(function(){  

  })

}(window.jQuery)

那样使用!重写上面的代码块

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


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


对于您的情况,您可以将工具提示代码简单地放入这样的文档就绪块中

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

它将正常工作.

如果只使用$("[rel=tooltip]").tooltip()而不使用任何doc ready block,则有可能在此代码运行时,DOM中还没有包含rel=tooltip的元素.因此$("[rel=tooltip]")将返回一个空集,而tooltip将不起作用.

一个示例标记,如果没有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>

作为浏览器,按顺序解释标记,它将在面对代码后立即执行js代码.而且,当它在此处执行JS块时,它尚未解析a rel="tooltip"标记,因为它出现在JS块之后,因此它们当时不在DOM中.

因此对于上述情况,$("[rel=tooltip]")为空,因此工具提示将不起作用.因此,将所有JS代码放入document ready块(如

)始终是安全的

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

希望所有这些对您现在都有意义.

I'm using twitter bootstrap to create a site and was trying to initialize tooltips. Apart from adding something like:

 $("[rel=tooltip]").tooltip()  

in application.js , unless I retain, the following piece of code used in bootstrap docs, my tooltips don't initialize.

!function ($) {

  $(function(){  

  })

}(window.jQuery)

What does the above code do?

解决方案

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 the 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.

这篇关于!function($){$(function(){})}(window.jQuery)是做什么的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆