Note: This article is just a summary of the various function definitions of JavaScript.
1. function declaration while the JS engine also defines a variable with the name of the function, we are actually using this variable when we call the function, and it can be called before the function declaration, such as
Foo (); This is actually using a function variable functions foo () {alert (' Hello ');}
2. Function expression, the anonymous function is assigned to a variable, which needs to be used after the definition, for example
Foo (); Error, undefined var foo = function () {alert (' Hello ');}
3. Functional expression (with function name), this usage is best avoided, this time not in IE Browser The function name is only available internally, for example
Bar (5); Error, undefined var bar = function foo (n) {if (n = 1) return 1; else return n * foo (n-1);} foo (5); Non IE error, not defined bar (5); That's right
4. Using function constructor definition, this method is inefficient , each time the function is executed, its function body will be parsed once. In addition, a function declared like this does not inherit the scope of the current declaration location, and it will only have global scope by default, for example
function foo () {var bar = ' Hello '; return Function (' Alert (bar) ');//error, global variable bar undefined} foo () ();