问题描述
我正在研究Immediatly Invoked Function Expressions(IIFE)的行为,在这样做时我遇到了以下情况。
I'am studying the behaviour of Immediatly Invoked Function Expressions (IIFE) and while doing that I encounterd the following situation.
(function () {
document.write("bar");
})
(function () {
document.write("foo");
}());
我认为第一个只是一个分组运算符,里面有一个函数表达式而没有调用它。第二个是分组运算符以及函数表达式,但现在调用该函数。
I thought that the first is just a grouping operator with a function expression inside without calling it. The second is a grouping operator as well with a function expression but now with the call of that function.
我觉得奇怪的是两者都被调用了,为什么会这样?
What I find strange is that both are invoked, why is that?
(function () {
document.write("bar");
})
var x = 1;
(function () {
document.write("foo");
}());
当我通过在两者之间插入变量声明来打破两者时,它只是写入foo。这就是我的预期。
When I break the two by inserting a variable declaration in between, it's just writes foo. This is what I expected.
推荐答案
因为你忘记了第一个函数表达式后面的分号:
Because you forgot the semicolon after the first function expression:
(function () {
document.write("bar");
});
否则第二个分组运算符被解释为函数调用。所以这个:
Otherwise the second "grouping operator" is interpreted as a function call. So this:
(function a() {
...
})
(function b() {
...
}());
基本相同:
function b() {
...
}
(function a() {
...
})(b());
重新排序让它更容易看到。请记住,空白字符在JavaScript中没有意义,会被忽略。
Reordering makes it a bit easier to see. Remember that white space characters have no meaning in JavaScript and are ignored.
这篇关于为什么立即调用此分组运算符+函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!