!function ($) { $(function(){ }) }(window.jQuery) 有什么作用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10896749/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 09:55:14  来源:igfitidea点击:

What does !function ($) { $(function(){ }) }(window.jQuery) do?

jqueryjquery-tooltip

提问by Grishma U

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

我正在使用 twitter bootstrap 创建一个站点,并试图初始化工具提示。除了添加类似的东西:

 $("[rel=tooltip]").tooltip()  
在 application.js 中,除非我保留引导程序文档中使用的以下代码段,否则我的工具提示不会初始化。

!function ($) {

  $(function(){  

  })

}(window.jQuery)

What does the above code do?

上面的代码有什么作用?

回答by Prasenjit Kumar Nag

Lets explain by Breaking up the code

让我们通过分解代码来解释

function () {
}()

Or often written as

或者经常写成

(function () {
})()

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

是一个self-invoking anonymous函数,也称为立即调用函数表达式 (IIFE)。立即执行内联匿名函数。

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

匿名函数是一项强大的功能,并且具有作用域(“变量名间距”)等优点,请参阅JavaScript 中自执行函数的目的是什么?.



Now they are using

现在他们正在使用

function ($) {

}(window.jQuery)

Let's skip the !for now.

让我们暂时跳过!

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

所以他们将,window.jQuery作为参数传入该函数并接受为$.

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

这样做是$window.jQuery(原始 jQuery 对象)创建一个别名,从而确保无论其他库是否将 that( )带到外部,$都将始终引用jQuery object内部的 that 。closure$

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 chainand 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 $.

另一个好处是它$作为匿名函数中的参数出现,这使它更接近于scope chain,因此 JS 解释器$在闭包中找到对象所需的时间比我们使用 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'swill work properly.

正如您可能已经知道的那样,它是 jQuery 的文档就绪块,它确保此函数中的代码将在 when 运行dom is ready,因此一切都event binding's将正常工作。

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

http://api.jquery.com/ready/阅读更多信息

And what that !does has been well explained hereor 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

如果您将上述代码粘贴到 中console,您将收到两个警报,但随后您将收到此错误

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 undefinedis returned inside the (). Same happens for the second function too. So after the execution of this block, it ends up having something like

为什么会发生这种情况?下面我们来模拟一下JS引擎是如何执行上述代码块的。它执行此匿名函数function() {alert('first');}()显示警报,并且由于它返回任何undefined内容,因此在(). 第二个函数也会发生同样的情况。所以在执行这个块之后,它最终会得到类似的东西

(undefined)(undefined)

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

由于它的语法就像一个self-invoking anonymous函数,它试图调用该函数,但第一个(undefined)不是函数。所以你得到undefined is not a function错误。!修复这种或错误。会发生什么!。我引用了上述答案链接中的行。

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.

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

这会强制将函数作为表达式求值,从而允许立即内联调用它。

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=tooltipin DOM yet. So $("[rel=tooltip]")will return an empty set and tooltipwon't work.

如果你只是使用$("[rel=tooltip]").tooltip()without any doc ready block,那么这段代码有可能运行时,rel=tooltipDOM 中还没有任何元素 with 。所以$("[rel=tooltip]")将返回一个空集并且tooltip不起作用。

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

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

作为浏览器,按顺序解释标记,它会在遇到它时立即执行 js 代码。并且当它在这里执行 JS 块时,它还没有解析a rel="tooltip"标签,因为它出现在 JS 块之后,所以它们此时不在 DOM 中。

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 readyblock like

所以对于上述情况$("[rel=tooltip]")是空的,因此工具提示将不起作用。所以把你所有的 JS 代码放在document ready块中总是安全的

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

Hope all this makes sense to you now.

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