Article Introduction: There are two ways to create functions in JavaScript: function declarations, function expressions. |
There are two ways to create a function in JavaScript: a function declaration, a function expression, each of which is written as follows:
Method One: function declaration
function foo () {}
Method Two: Expression of function
var foo = function () {};
There is also a custom function expression that is used primarily to create a new scope in which variables declared within the scope
Do not conflict with or confuse variables in other scopes, mostly in anonymous functions, and are automatically executed immediately:
(function () {
var x = ...
})();
This kind of function expression is categorized as the second of the above two methods and is also considered as a function expression.
Both method one and method two create a function that is named Foo, but there is a difference.
There is a mechanism in the JAVASCRIPT interpreter for a variable declaration to be promoted (hoisting) , which means that the variable
The Declaration of the (function) is promoted to the front of the scope, even when the code is written at the end, or
will be elevated to the front .
For example, the following code snippet:
Alert (foo); function foo () {}
alert (bar); Undefined
function foo () {}
var bar = function Bar_fn () {};
Alert (foo); function foo () {}
alert (bar); function Bar_fn () {}
Output results are function foo () {}, undefined, function foo () {}, and function
Bar_fn () {}.
You can see that Foo's declaration is written after alert and can still be called correctly because JavaScript explains
The device will elevate it to the front of alert, and the function bar created with the function expression does not enjoy this treatment.
So whether bar has been promoted, in fact, the variables declared with VAR will be promoted, but is to be first assigned
For undefined, so the second alert pops up undefined.
So the sequence of the JavaScript engine executing the above code might be this:
Create variable foo and bar, and assign them all to undefined.
Create the function body of the function foo and assign it to variable foo.
Executes the previous two alert.
Create a function bar_fn and assign it to bar.
Executes the following two alert.
Note:
Strictly speaking, there is another way to create a function in JavaScript, called the function constructor:
var foo = Function (' Alert (' hi! ');
var foo = new Function (' Alert (' hi! '); Equal to the line above
This method forms a function body with a string as a parameter. But in this way, the efficiency of execution will be compromised,
And it doesn't seem to be able to pass arguments, so it's better to use less.