Javascript匿名函数调用 [英] Javascript anonymous function call
问题描述
我正在阅读Twitter上的JS资源—在我改善我的JS知识库的路上,当我遇到调用匿名函数的奇怪方式时:
I was reading JS sources from Twitter — on my way to improve my JS knowledge base, when I came across the strange way of calling anonymous function:
!function( $ ) {
...
}( window.jQuery );
......这都有效! :)
... and this works! :)
每个人都很明显,这个:
It's obvious to everyone, that this:
function ( $ ) { ... } ( window.jQuery )
不起作用(语法错误),虽然这是正确的:
does not work (Syntax error), while this one is correct:
(function ( $ ) { .... })( window.jQuery )
任何人都可以解释这个魔法(为什么的情况!函数
工作)?
Can anyone please explain this magic (why case with !function
works)?
推荐答案
当满足关键字 function
时语句位置(作为语句中的第一个标记),函数声明表示为函数语句。函数语句被提升到作用域的顶部,不能立即调用并且必须具有名称。
When the keyword function
is met in a statement position (as the first token in a statement), the function declaration is expressed as a function statement. Function statements are hoisted to the top of the scope, cannot be immediately invoked and must have a name.
当在表达式位置满足关键字时(即不作为语句中的第一个标记,在您的示例中!
是第一个标记),函数声明表示为函数表达式,可以是匿名的并返回新创建的函数的值。因为它返回新创建的函数的值,所以你可以通过在它之后添加括号来立即调用它。
When the keyword is met in an expression position (i.e. not as the first token in a statement, in your example !
is the first token), the function declaration is expressed as a function expression, which may be anonymous and returns the value of the newly created function. Since it returns the value of the newly created function, you may immediately invoke it by adding parenthesis after it.
将括号内的声明包装起来也是一样的但是比前缀为!
或 +
:
Wrapping the declaration inside parenthesis does the same but is more common than prefixing it with a !
or +
:
(function () {
...
}());
这篇关于Javascript匿名函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!