This article mainly describes the differences between JavaScript functions defined by function statements and expressions. Need friends can come to the reference, I hope to help you.
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 functions: code as follows://Function statement functions fn (str) { Console.log (str); //Expression definition var fnx=function (str) { Console.log (str+ ' from Fnx '); used to use both of their own fingers-_-| | , today read the JS Foundation, finally solved the heart of their confusion: Two methods have created a new function object, but the function declaration statement's function name is a variable name, the variable points to the function object, and through the Var declaration variable, Functions in a function definition statement are displayed in advance to the top of a script or function. So they are all visible within the entire script and function, but using the var expression to define the function, only the variable declaration is advanced, the variable initialization code is still in the original position, the function name and function body are created in advance , so we can use it before declaring it. Code examples are as follows: code is as follows: console.log (typeof (FN)); function FN (' abc '); ABC Console.log (typeof (FNX)); Undefined if (FNX) FNX (' abc '); //won't 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 the same as I did not understand the difference between the students can gain.