JS Elevation 7. Function Expressions (1)

Source: Internet
Author: User

There are two common ways to define functions:

1. function declaration

2. Function expressions

# differences

(1) function declaration, which has the feature of function declaration promotion.

(2) The Name property of the function declaration function is the names of the functions; functions defined with function expressions in ES5, the Name property is an empty string, and the name of the function in ES6.

# function Declaration Promotion

function declaration

1 SayHello (); // calling a function before the function declaration does not cause an error because the function declaration is promoted.  2function  SayHello () {3     console.log ("hello!"); // hello! 4     Console.log (Sayhello.name); // SayHello 5 }

function expression

 1  SayHello (); //  Typeerror:sayhello is not a function uses the method of a function expression to define functions, and calling a function before a variable declares a function will cause an error.  2  var  SayHello = function   () { 3  Console.log ("hello!"); // hello!  4  console.log (sayhello.name); // sayhello. Note: In ES5, the Name property of the anonymous function is an empty string (P176), which returns the original name of the named function in ES6.  5  }   6  SayHello (); //  

# Note the following situation

1 //don't do that. Because of the reason for the function declaration promotion, the following code is invalid in ECMAScript, and the browser tries to fix the error in an inconsistent manner. P1762  varFlag =true;3  if(flag) {4      functionSayhi () {5Console.log ("Hi");6      }7}Else{8      functionSayhi () {9Console.log ("Yo");Ten      } One  } ASayhi ();//Strict mode will error. Referenceerror:sayhi is not defined

1 //You can do this by using a function expression. 2  varFlag =true;3  varSayhi;4  if(flag) {5Sayhi =function(){6Console.log ("Hi");7      }8}Else{9Sayhi =function(){TenConsole.log ("Yo"); One      } A  } -Sayhi ();

JS Elevation 7. Function Expressions (1)

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.