Home > Web Front-end > JS Tutorial > Summary of common considerations for JavaScript function definition_javascript tips

Summary of common considerations for JavaScript function definition_javascript tips

WBOY
Release: 2016-05-16 16:36:22
Original
1214 people have browsed it

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

1. When the function is declared, 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 is declared, such as

foo(); //这里实际上是使用了一函数变量 
function foo() { 
  alert('hello'); 
} 

Copy after login

2. Function expression. At this time, the anonymous function is assigned to a variable. This variable needs to be used after being defined, such as

foo(); //报错,未定义 
var foo = function() { 
  alert('hello'); 
} 

Copy after login

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, such as

bar(5); //报错,未定义 
var bar = function foo(n) { 
  if (n == 1) 
    return 1; 
  else 
    return n * foo(n - 1); 
} 
foo(5); //非IE报错,未定义 
bar(5); //正确 
Copy after login

4. Define using Function constructor. This method is inefficient. Every time the function is executed, its function body will be parsed. In addition, a function declared in this way will not inherit the scope of the current declaration position. It will only have the global scope by default, such as

function foo() { 
  var bar = 'hello'; 
  return Function('alert(bar)'); //报错,全局变量bar未定义 
} 
foo()();

Copy after login

I believe that what is described in this article has certain reference value for everyone’s learning of javascript WEB programming.

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template