Differences between the two definition methods of JS and Internal principles

Source: Internet
Author: User

I believe that the two methods have been used by everyone, but not everyone may know the difference and Internal principles.
Copy codeThe Code is as follows:
// Method 1
Function func1 (x, y ){
// Your code
}
// Method 2
Var func2 = function (x, y ){
// Your code
}

Method 1 is a typical Function declaration ).
Method 2 is a Function expression that assigns an anonymous Function to a variable. Or create an anonymous function with the form parameter x and y in method 2, and assign the value to the variable func2.

The main difference is:
1. The specified function name to be displayed in the function declaration. Here it is func1. The function expression uses the anonymous function.
2. method 1 is loaded into the scope before Code Execution (Interpretation period), and method 2 is loaded at Code Execution (runtime ).

A simple example shows the differences in their usage.
Copy codeThe Code is as follows:
Alert (func1); // --> func1 source code
Alert (func2); // --> undefined
// Method 1
Function func1 (x, y ){
// Your code
}
// Method 2
Var func2 = function (x, y ){
// Your code
}

As you can see, the first pop-up is the source code of func1, but the second is undefined. That is, the method 1 (function declaration) is used to define a function. You can use it on the code of this function. If the method 2 (function expression) is used to define a function, it cannot be used before its definition, it can only be used after its definition.

It involves the Execution context and Activation object ). For more information, see EcmaScript 5.

Recently, more and more people prefer to use method 2 to define functions, especially nested functions. For example, simply defining a function is still a habit of method 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.