This article summarizes the common problems with JavaScript function definitions. Contains the mistakes that beginners often make. Share to everyone for your reference. The concrete summary is as follows:
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); No bar (5) is defined without IE error
.//correct
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 () ();
It is believed that this article has certain reference value to everyone's learning of JavaScript Web programming.