JavaScript / jQuery 闭包函数语法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4472528/
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-23 12:34:12  来源:igfitidea点击:

JavaScript / jQuery closure function syntax

javascriptjquery

提问by MBax

Can someone please explain the differences between the following functions:

有人可以解释以下功能之间的区别吗:

(function($){
  // can do something like 
  $.fn.function_name = function(x){};

})(jQuery);

Could I use jQuery in the next function?

我可以在下一个函数中使用 jQuery 吗?

(function(){

}());

And is the following the same as jquery.ready()?

以下是否与 jquery.ready() 相同?

$(function(){

});

Thanks!

谢谢!

回答by Sarfraz



(function($){
  // can do something like 
  $.fn.function_name = function(x){};

})(jQuery);

That is self-executing anonymous function that uses $in argument so that you can use it ($) instead of jQueryinside that function and without the fear of conflicting with other libraries because in other libraries too $has special meaning. That pattern is especially useful when writing jQuery plugins.

这是$在参数中使用的自执行匿名函数,因此您可以使用它 ( $) 而不是jQuery在该函数内部,并且不必担心与其他库发生冲突,因为在其他库中也$有特殊含义。这种模式在编写 jQuery 插件时特别有用。

You can write any character there instead of $too:

你可以在那里写任何字符而不是$太:

(function(j){
  // can do something like 
  j.fn.function_name = function(x){};

})(jQuery);

Here jwill automatically catch up jQuery specified at the end (jQuery). Or you can leave out the argument completely but then you will have to use jQuerykeyword all around instead of $with no fear of collision still. So $is wrapped in the argument for short-hand so that you can write $instead of jQueryall around inside that function.

这里j会自动追上 jQuery 指定的末尾(jQuery)。或者您可以完全省略参数,但是您将不得不jQuery到处使用关键字,而不是$仍然不必担心碰撞。So$包含在简写的参数中,以便您可以在该函数内部编写$而不是在jQuery周围编写。



(function(){

}());

That is self-executing anonymous function again but with no arguments and runs/calls itself because of ()at the end.

这又是一个自动执行的匿名函数,但没有参数并且因为()最后而运行/调用自己。

That patterns turns out to be extremely useful in some situations. For example, let's say you want to run a piece of code after 500 milli seconds each time, you would naturally go for setInterval.

事实证明,这种模式在某些情况下非常有用。例如,假设您想在每次 500 毫秒后运行一段代码,您自然会选择setInterval.

setInterval(doStuff, 500);

But what if doStufffunction takes more than 500 mill-seconds to do what it is doing? You would witness unexpected results but setIntervalwill keep on calling that function again and again at specified time irrespective of whether doStufffinished.

但是如果doStuff函数需要超过 500 毫秒来完成它正在做的事情呢?你会看到意想不到的结果,但setInterval无论是否doStuff完成,都会在指定的时间一次又一次地调用该函数。

That is where that pattern comes in and you can do the same thing with setTimeoutin combination with self-executing anonymous function and avoid badsetIntervallike this:

这就是该模式的用武之地,您可以setTimeout结合自执行匿名函数来做同样的事情,并避免像这样的坏事setInterval

(function foo(){
   doStuff;

   setTimeout(foo, 500);

})()

This code will also repeat itself again and again with one difference. setTimeoutwill never get triggered unless doStuffis finished. A much better approach than using bad setInterval.

这段代码也会一次又一次地重复,但有一个区别。setTimeout除非doStuff完成,否则永远不会被触发。比使用 bad 更好的方法setInterval

You can test it here.

你可以在这里测试。

Note that you can also write self-executing anonymous function like this:

请注意,您还可以像这样编写自执行匿名函数:

function(){
  // some code
}();

Using extra braces around (like before functionkeyword) is simply coding conventionand can be seen in Crackford's writings, jQuery and elsewhere.

在周围使用额外的大括号(如 beforefunction关键字)只是编码约定,可以在 Crackford 的着作、jQuery 和其他地方看到。



$(function(){

});

That is short-hand syntax for ready handler:

这是就绪处理程序的简写语法:

$(document).ready(function(){

});

More Information:

更多信息:

回答by Sunyatasattva

I know that this question is old, but I stumbled upon it right now and so may other people. I just wanted to point out that, although Sarfraz's answer is great, it has to be said that no, writing a self-executing, anonymous functionwithin braces is nota coding convention.

我知道这个问题很老,但我现在偶然发现了它,其他人也可能如此。我只是想指出的是,虽然Sarfraz的答案是伟大的,但必须说,没有,写一个自动执行的,匿名函数括号内是不是一个编码约定

function(){
  // some code
}();

Will not work and give out a SyntaxErrorbecause the function is being parsed as a FunctionDeclaration, and the function name is not optionalin this case.

不会工作并给出 aSyntaxError因为函数被解析为 a FunctionDeclaration,并且在这种情况下函数名称不是可选的

On the other hand, the Grouping Operatormakes sure that the content is evaluated as a FunctionExpression.

另一方面,分组运算符确保内容被评估为FunctionExpression.

See:Explain JavaScript's encapsulated anonymous function syntax

请参阅:解释 JavaScript 的封装匿名函数语法