If you need to create a function in JavaScript, there are two methods: functional declaration, function expression, each writing is as follows:
// Method 1: Functional declaration foo () {} // Method 2: Function expression var foo = function () {};In addition, there is a self -executed function expression, which is mainly used to create a new scope. The variables declared in this scope will not conflict or confuse the variables in other fields. implement:
(function () {// var x = ...}) ();This self -executed function expression is classified as the second method of the above two methods, which can also be regarded as functional expression.
Methods 1 and Method II created a function and named it FOO, but there are differences between the two. There is a mechanism that exists in the JavaScript interpreter that is promoted (Hoisting), which means that the statement of a variable (function) will be promoted to the forefront of the scope. It was promoted to the forefront.
For example, the following code segment:
alert (foo); // function foo () {} alert (bar); // undefinedfunction foo () {} var bar = function bar_fn () {}; // function foo () {} Alerr T (BAR); // Function bar_fn () {}The output results are functions foo () {}, undefined, functions foo () {}, and function bar_fn () {}.
It can be seen that the Foo's statement is written after Alert, and it can still be correctly called because the JavaScript interpreter will raise it to the front alert, and the function BAR created by the function expression does not enjoy this treatment.
So is BAR being improved? The practical VAR declaration variable will be improved, but it is only assigned to UNDEFINED, so the second Alert pops upfined.
Therefore, the order of the above code of the JavaScript engine may be like this:
Note:
Strictly speaking, if you create a function in JavaScript, there is another method, called the "function structure method":
var foo = function ('alert ("hi!");'); var foot = new function ('alert ("hi!"); // equivalent to the above line above This method uses a string as a parameter to form a function body. However, in this method, the execution efficiency will be discounted, and it seems that the parameters cannot be passed, so it is better to use less.