I have been using javascript for many years and have written countless functions, but today I have really understood the differences between the two function definitions. It is really a tragedy. I wrote this article to remind myself to lay a solid foundation at all times, you are too old to be ignorant.
We usually see the following two methods to define functions:
Copy codeThe Code is as follows:
// Function statement
Function fn (str)
{
Console. log (str );
};
// Expression Definition
Var fnx = function (str)
{
Console. log (str + 'from fnx ');
};
In the past, I used to use both-_-| as I felt by my fingers. Today I read the js basics and finally solved their confusion:
Both methods create a new function object, but the function name of the function declaration statement is a variable name. The variable points to the function object, just like declaring a variable through var, the functions in the Function Definition Statement are displayed at the top of the script or function, so they are visible throughout the script and function, but the var expression is used to define the function, only when the variable declaration is in advance, the variable initialization code is still in the original position. functions created using function statements, function names, and function bodies are both in advance, so we can use it before declaring it.
The code example is as follows:
Copy codeThe Code is as follows:
Console. log (typeof (fn); // function
Fn ('abc'); // abc
Console. log (typeof (fnx); // undefined
If (fnx)
Fnx ('abc'); // will not execute
Else
Console. log ('fnx is undefined'); // fnx is undefined
// Function statement
Function fn (str)
{
Console. log (str );
};
// Expression Definition
Var fnx = function (str)
{
Console. log (str + 'from fnx ');
};
The code is very simple. I hope that you will be able to get something better if you don't understand the difference between the two.