There are two ways to declare functions in javascript: function declarations and function expressions.
The difference is as follows:
1. Functions defined by the method declared by the function, the function name is required, and the function expression of the function name is optional.
2. Functions defined by the method declared by the function, functions can be called before the function declaration, and function expression functions can only be called after the declaration.
3. Functions defined by the method of the function declaration are not true declarations, they can only appear in the global, or nested in other functions, but they can not appear in the loop, condition or try/catch/finally, and
A function expression can be declared anywhere.
There are two ways to define a function, respectively:
Copy Code code as follows:
Function-declaration
function greeting () {
Console.log ("Hello World");
}
function expression
var greeting = function () {
Console.log ("Hello World");
}
Here's an interesting javascript:
Copy Code code as follows:
function f () {Console.log (' I am outside! ');}
(function () {
if (false) {
Repeat declaration once function f
function f () {Console.log (' I am inside! ');}
}
f ();
}());
What does it output? The first reaction should be "I am outside". Results in chrome output "I am inside", IE11 direct error, Firefox lower version of the output "I am outside" ...
The results of the chrome output clearly reflect the features of functions declared with function declarations-functions that can be invoked before they are declared.
The IE error shows missing objects because the function declaration is in the condition and violates the principle of the function declaration.
Scope of function Expressions:
If a function expression declares a function that has a function name, then the function name is equivalent to a local variable of this function, which can only be invoked inside the function, lifting a chestnut:
Copy Code code as follows:
var f = function fact (x) {
if (x <= 1)
return 1;
Else
Return X*fact (x-1);
};
Alert (fact ()); Uncaught referenceerror:fact is not defined
Fact () can be invoked inside a function, and an error is invoked outside the function: fact undefined
The above is the entire content of this article, I hope you can enjoy.