自调函数的括号符号是否有助于Javascript的目的? [英] Does parenthetical notation for self-invoked functions serve a purpose in Javascript?
问题描述
(function(){} {}当我在Javascript中看到自引用的匿名函数的例子时,我感到困惑。 return val;})();
这个语法和下面的语法有什么不同:
function(){return val;}();
如果有人能给我一个具体的区别,这将有助于解决一直困扰着我的问题长久以来...
Javascript没有块范围,所以这是一种创建临时局部范围的方法这不会污染全局名称空间。括号有两个作用:
- 如果缺少某些javascript实现,它们会被翻转。
- 它向读者表明与正常的函数声明不同的东西正在发生。所以作为一个约定,它表明这个函数被用作范围。
请看这里:
http://peter.michaux.ca/articles/an-important-pair-of -parens
I get confused when I see examples of self invoked anonymous functions in Javascript such as this:
(function () { return val;}) ();
Is there a difference between this syntax and the following:
function() { return val;} ();
If someone can give me a concrete difference, it would help put to rest a question that's been bugging me for ages...
Javascript doesn't have a block scope, so this is a way to create a temporary local scope that doesn't pollute the global namespace. The parentheses serve two purposes:
- Some implementations of javascript flip out if they're missing.
- It signals to readers that something different from a normal function declaration is going on. So as a convention, it signals that this function is being used as a scope.
see here: http://peter.michaux.ca/articles/an-important-pair-of-parens
这篇关于自调函数的括号符号是否有助于Javascript的目的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!