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
252 views
in Technique[技术] by (71.8m points)

javascript - Difference between a named IIFE and calling a name function immediately?

Is there any difference between and IIFE

(function foo () {
    var var_of_concern;
}());

and a plain function

function foo () {
   var var_of_concern;
}
foo();

The caveat that concerned me, was if I pass nothing out of either the IIFE or the function, will the IIFE keep the memory alive longer?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

The opposite, though it's probably not a serious concern.

The two are syntactically not the same. The second declares a function and binds it to the local symbol "foo". That function will remain after the function call.

The IIFE form is syntactically a single expression satement. The second form involves two statements, a function declaration statement and an expression statement (the function call).

The way that a function call handles local variable declarations has nothing to do with how the function object came into being. If both functions in your example are the same, then there's no difference to how that space is allocated for the local variables in a function call.

edit — the key syntactic difference is this: the keyword function at the start of a new statement introduces a function declaration statement. That syntactic form does not provide for immediate invocation. That is, this:

function hello() {
  // some code
}();  // <---- ERROR

is a syntax error.

When the function keyword appears in any other context (well, any valid context), then it's not a function declaration — it's a function instantiation (or function definition; I'd have to check the spec) expression. These are all things that can be part of an expression in JavaScript:

 5
 "hello"
 false
 (2 + 5)
 (function() { alert("Hi!"); })

Note that the last example involves parentheses - that's commonly done to "defuse" the "Oh look a function declaration!" behavior of the parser. That opening parenthesis means that the function keyword does not appear at the absolute beginning of the statement, so it's therefore just a function instantiation expression.


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

...