Common considerations for JavaScript function definitions Summary _javascript tips

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.