解释了自执行函数语法和回调语法 [英] Self-executing function syntax and callback syntax explained
问题描述
但是我想理解为什么自执行函数的语法和它所具有的回调是如此不同于所有其他JS语法..
(function(){
})()
我只需要理解为什么用封装它是有效的()
我不会我猜测它是有效的,然后是额外的()
之后的回调,(它只是直接位于它之后,我也不会想到它是有效的。
有人能够向我解释这个吗?
函数(...){...}
part是函数表达式,即表示函数的表达式。在这种情况下,必须用括号括起来的唯一原因是,如果关键字 function
是语句中的第一个内容,那么该语句将被假定为功能状态t ,即函数声明。 (实际上,它不一定要用括号括起来;它也可以用 +
作为前缀,或者通常在<$之前放置任何类型的令牌c $ c> function 阻止函数语句解释。)
()
函数表达式之后的部分与用于调用函数的普通()
相同。这:
(function(...){...})(...);
(除临时变量外)与此相同:
var f = function(...){...};
f();
相当于:
function f(...){...};
f();
bit of a silly question perhaps.
But I want to understand why the syntax on the self-executing function and the callback it has is so different to all the other JS syntax..
(function () {
})()
I just need to understand why its valid to encapsulate it with ()
I wouldn't have guessed that to be valid, and then the extra ()
afterwards for the callback, (which just sits directly after it, I also wouldn't have expected that to be valid.
Is anyone able to explain this to me?
The function (...) {...}
part is a function expression, that is, an expression that represents a function. The only reason it has to be wrapped in parentheses in this case is that if the keyword function
is the very first thing in a statement, then the statement is assumed to be a function statement, that is, a function declaration. (Actually, it doesn't necessarily have to be wrapped in parentheses; it also works to prefix it with a +
, or in general to put any sort of token before function
that prevents the function-statement interpretation.)
The ()
part after the function expression is the same as the normal ()
for calling a function. This:
(function (...) {...})(...);
is (aside from the temporary variable) the same as this:
var f = function (...) {...};
f();
which is equivalent to this:
function f(...) {...};
f();
这篇关于解释了自执行函数语法和回调语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!