Function declaration
Function assignment expression
Assignment expression for named function
# Functions are first-class objects in JavaScript, which means they can be passed around like any other value. A common usage is to pass an anonymous function as a callback function into an asynchronous function.
Function declaration
function foo() {}
The above method will be parsed (hoisted) before execution, so it exists anywhere in the current context, even if it is called above the function definition body, it is correct of.
foo(); // 正常运行,因为foo在代码运行前已经被创建 function foo() {
Function assignment expression
var foo = function() {};
This example assigns an anonymous function to variable foo.
foo; // 'undefined' foo(); // 出错:TypeError var foo = function() {};
Since var defines a declaration statement, the variable foo is parsed before the code is run, so the foo variable has already been defined when the code is running.
But since the assignment statement is only executed at runtime, the value of foo defaults to undefined before the corresponding code is executed.
Assignment expression of named function
Another special case is to assign the named function to a variable.
var foo = function bar() { bar(); // 正常运行 } bar(); // 出错:ReferenceError
bar The function declaration is invisible outside, because we have assigned the function to foo; however, it is still visible inside bar. This is due to JavaScript's naming processing. Function names are always visible within functions.
Note: In browsers IE8 and below, bar is also visible externally because the browser incorrectly parses the named function assignment expression and parses it into two functions foo and bar
The above is the content of the JavaScript advanced series - function declarations and expressions. For more related content, please pay attention to the PHP Chinese website (m.sbmmt.com)!