Javascript匿名函数调用 [英] Javascript anonymous function call

查看:35
本文介绍了Javascript匿名函数调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从 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 );

...这有效!:)

这对每个人来说都是显而易见的:

It's obvious to everyone, that this:

function ( $ ) { ... } ( window.jQuery )

不起作用(语法错误),而这个是正确的:

does not work (Syntax error), while this one is correct:

(function ( $ ) { .... })( window.jQuery )

谁能解释一下这个魔法(为什么!function 的情况下有效)?

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屋!

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