This article summarizes common problems in javascript function definition. It contains common mistakes made by beginners. Share it for your reference. The specific summary is as follows:
1. At the same time as the function declaration, the JS engine also defines a variable with the same name as the function name. When we call this function, we are actually using this variable, and it can be called before the function declaration, for example
foo(); //A function variable is actually used here function foo() { alert('hello'); }2. Function expression, at this time, the anonymous function is assigned to a variable, which needs to be used after definition, for example
foo(); //An error is reported, undefined var foo = function() { alert('hello'); }3. Function expression (with function name), this usage is best avoided. At this time, the function name is only available internally in non-IE browsers, for example
bar(5); //An error is reported, undefined var bar = function foo(n) { if (n == 1) return 1; else return n * foo(n - 1); } foo(5); //Not IE error is reported, undefined bar(5); //Correct4. Definition with Function constructor, this method is inefficient. Every time a function is executed, its function body will be parsed once. In addition, the function declared in this way will not inherit the scope of the current declared location. It will only have a global scope by default, for example
function foo() { var bar = 'hello'; return Function('alert(bar)'); //An error is reported, the global variable bar is not defined} foo()();I believe that the description in this article has certain reference value for everyone's learning of javascript WEB programming.