In ECMAScript, the two most common methods for creating a function are function expressions and function declarations.
In ECMAScript, the two most common methods for creating a function are function expressions and function declarations. The difference between the two methods is a bit dizzy, because the ECMA specification only makes it clear: the function declaration must contain an Identifier (the name of a function that is commonly used), while the function expression can omit this Identifier:
Function declaration:
Function Name (parameter: OPTIONAL) {function body}
Function expression:
Function Name (optional) (parameter: OPTIONAL) {function body}
Therefore, we can see that if the function name is not declared, it must be an expression. If the function name is declared, how can we determine whether it is a function declaration or a function expression? ECMAScript is distinguished by context. If function foo () {} is a part of the value assignment expression, it is a function expression. If function foo () {} is contained in a function, or at the top of the program, it is a function declaration.
Function foo () {}// declaration, because it is part of the program var bar = function foo () {}; // expression, because it is a part of the value assignment expression new function bar () {}; // expression, because it is a new expression (function () {function bar () {}// declaration, because it is part of the function body })();
Another function expression is not very common, that is, function foo () {}) enclosed by brackets. It is the reason for the expression because parentheses () are a grouping operator, it can only contain expressions. Let's look at several examples:
Function foo () {}// function declaration (function foo () {}); // function expression: include in the grouping operator try {(var x = 5 ); // grouping operator, which can only contain expressions but not statements: the var here is the statement} catch (err) {// SyntaxError}
You can think that when using eval to execute JSON, The JSON string is usually included in a parentheses: eval ('+ json + ')'), the reason for doing so is that the grouping operator, that is, this pair of parentheses, will force the parser to parse the JSON curly braces into expressions rather than code blocks.
Try {"x": 5}; // "{" and "}" are parsed into code blocks} catch (err) {// SyntaxError} ({"x ": 5}); // The grouping operator forcibly parses "{" and "}" as the object literal.
There are very subtle differences between expressions and declarations. First, the function declaration will be parsed and evaluated before any expression is parsed and evaluated, even if your declaration is on the last line of the Code, it will also be parsed/evaluated before the first expression in the same scope. For example, the fn function is declared after alert, but when alert is executed, fn has been defined:
alert(fn());function fn() {return 'Hello world!';}
In addition, you need to note that function declaration can be used in conditional statements but is not standardized. That is to say, different environments may have different execution results. In this case, it is best to use a function expression:
// Never do this! // Some browsers return the first function, while some browsers return the second if (true) {function foo () {return 'first ';}} else {function foo () {return 'second';} foo (); // opposite. In this case, we use the function expression var foo; if (true) {foo = function () {return 'first ';};} else {foo = function () {return 'second' ;};} foo ();
The actual rules of the function declaration are as follows:
Function declarations can only appear in programs or functions. Syntactically, they cannot appear in blocks (blocks) ({...}). for example, they cannot appear in if, while, or for statements. Because the Block can only contain Statement statements, but cannot contain source elements such as function declaration. On the other hand, if you take a closer look at the rule, you will also find that the only possible reason for the expression to appear in the Block is to make it part of the expression statement. However, the specification clearly stipulates that expression statements cannot start with a function keyword. In fact, function expressions cannot appear in Statement statements or blocks (because blocks are composed of Statement statements ).
Additional reading
The topic list of this article is as follows:
- How should we understand the working principle of the JavaScript engine?
- JavaScript exploration: the importance of writing maintainable code
- JavaScript exploration: exercise caution when using global variables
- JavaScript exploration: var pre-parsing and side effects
- JavaScript exploration: for Loop (for Loops)
- JavaScript exploration: for-in loop (for-in Loops)
- Exploring JavaScript: Prototypes is too powerful
- JavaScript: eval () is the devil"
- JavaScript exploration: Using parseInt () for Numerical Conversion
- Exploring JavaScript: Basic coding specifications
- JavaScript exploration: function declaration and function expression
- JavaScript exploration: Name function expressions
- JavaScript: function name in the debugger
- JavaScript: JScript Bug
- JavaScript exploration: Memory Management of JScript
- Exploring JavaScript: SpiderMonkey's quirks
- JavaScript exploration: an alternative solution to naming function expressions
- JavaScript exploration: Object
- JavaScript exploration: Prototype chain
- JavaScript exploration: Constructor
- JavaScript probing: executable context Stack
- Execution context 1: Variable object and activity object
- Execution context 2: Scope chain Scope Chains
- Execution context 3: Closure Closures
- Execution context 4: This pointer
- Exploring JavaScript: Powerful prototype and prototype chain
- JavaScript Functions 1: function declaration
- JavaScript function 2: function expressions
- JavaScript function 3: function expressions in a group
- JavaScript function 4: function Constructor
- JavaScript variable object 1: VO Declaration
- JavaScript variable object 2: VO in different execution contexts
- JavaScript variable object 3: two stages of execution Context
- JavaScript variable object IV: Variables
- Property of the JavaScript variable object __parent _
- JavaScript scope chain 1: Scope chain Definition
- JavaScript scope chain 2: function Lifecycle
- JavaScript scope chain 3: Scope chain features
- JavaScript closure 1: Introduction to closures
- JavaScript closure 2: Implementation of closure
- JavaScript closure 3: Closure usage
This article is available at http://www.nowamagic.net/librarys/veda/detail/1630.