Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
308 views
in Technique[技术] by (71.8m points)

javascript - Why is this grouping operator + function immediately invoked

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");
}());

When I break the two by inserting a variable declaration in between, it's just writes foo. This is what I expected.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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() {
    ...
}());

is basically the same as:

function b() {
    ...
}

(function a() {
    ...
})(b());

Reordering makes it a bit easier to see. Remember that white space characters have no meaning in JavaScript and are ignored.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...