Using JavaScript for many years, wrote countless functions, today but really understand the difference between the definitions of the two functions, is really a tragedy, write down this essay, to remind themselves to lay a good foundation, a lot of age, can not continue to be ignorant.
Usually we see the following two ways to define a function:
Copy Code code as follows:
Function statement
function fn (str)
{
Console.log (str);
};
An expression definition
var fnx=function (str)
{
Console.log (str+ ' from Fnx ');
};
Used to be the feeling of their own fingers to use both-_-| | , today read the JS Foundation, finally solved the hearts of their confusion:
A new function object is created in both ways, but a function declaration statement has a function name that is a variable name, a variable to a function object, and, as with VAR declaration variables, functions in a function definition statement are displayed in advance to the top of the script or function, so they are visible throughout the script and function, but using the Var Expression definition function, only the variable declaration is advanced, the variable initialization code is still in the original position, functions created with Function statement, function name and function body are all advanced, so we can use it before declaring it.
The code example is as follows:
Copy Code code as follows:
Console.log (FN) (typeof); function
FN (' abc '); Abc
Console.log (typeof (FNX)); Undefined
if (FNX)
FNX (' abc '); Would not execute
Else
Console.log (' fnx is undefined '); FNX is undefined
Function statement
function fn (str)
{
Console.log (str);
};
An expression definition
var fnx=function (str)
{
Console.log (str+ ' from Fnx ');
};
The code is very simple, hope and I did not understand the difference between the two students can gain.