Summary of common considerations for JavaScript function definitions

  • 2020-03-30 03:58:21
  • OfStack

This article summarizes common problems with javascript function definitions. Contains common mistakes made by beginners. Share with you for your reference. The specific summary is as follows:

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(); //I'm actually using a function variable here
function foo() { 
  alert('hello'); 
} 

2. Function expression, which assigns an anonymous function to a variable that needs to be used after definition, for example


foo(); //Error report, undefined
var foo = function() { 
  alert('hello'); 
} 

3. Function expression (with function name). This use is best avoided as the function name is only available internally in non-ie browsers, for example


bar(5); //Error report, undefined
var bar = function foo(n) { 
  if (n == 1) 
    return 1; 
  else 
    return n * foo(n - 1); 
} 
foo(5); // non IEError report, undefined
bar(5); // correct  

4. The Function constructor is an inefficient way to define a Function. Every time a Function is executed, the body of the Function will be parsed. In addition, such a declared function does not inherit the scope of the current declared location, it only has global scope by default, for example


function foo() { 
  var bar = 'hello'; 
  return Function('alert(bar)'); //Error reported, global variable bar undefined
} 
foo()();

I believe that this article has a certain reference value to the study of javascript WEB programming.


Related articles: