JS execution Order-function declaration promotion, anonymous function, function expression

Source: Internet
Author: User
Tags variable scope

In the general direction: JS is compiled and executed according to the code block. Learn to:
    • 1. Variable declaration Promotion
    • 2. New Tang's Blog
    • Analysis of creation and invocation method of anonymous function in 3.js
    • 4. Front-end Bible-Gao Cheng
    • 5. In-depth understanding of variable declaration promotion and Function declaration promotion
Because it is not properly categorized. may be more miscellaneous. To learn in a systematic way, first understand several concepts. One. <script>Blocks of code that are differentiated.

JS is compiled and executed according to the code block. Code blocks are independent of each other, but variables and methods are shared.

<script>  alert('代码块一');</script><script>  alert('代码块二');</script>
<script>  var a = 3;</script><script>  console.log(a); // 3</script>
Two. About functions (declarative functions, assignment functions, anonymous functions, self-executing functions)
  • declarative functions and assignment-style functions

    The difference between a declaring function and an assignment function is that, during the pre-compilation of JS, the declarative function is extracted first and then the JS code is executed in sequence.

    Declarative:

    A();  // 'A 'function A() {  console.log('A');}

    Assignment Type:

    B(); // error, B is not a functionvar B = function() {  console.log('B');}
  • What is an anonymous function?

    A function without a name is an anonymous function.

    function() {} // 匿名函数
  • What is a self-executing function

    (function() {  console.log(3);})();

    Note that the following notation will be an error

    function() {  console.log(3);}();
    The reasons are as follows:
    1. function {}()This is actually a function declaration.
    2. When JS runs, the function declaration is precompiled, and then other statements are executed.
    3. In other words function(){} , it is precompiled first. Then JS saw it () . JS a face confused force, this must not error.
    4. The anonymous function is actually a statement that executes normally.

    It is also necessary to know that the identity of the self-executing function can be

    !function(){}()              (function(){})()     ~function(){}()      void function(){}()

    Self-executing functions are available with parameters, and the format is like this!

    function(num){  console.log(num);}(3);              // 3
Three. Pre-compilation period and execution period

In fact, the parsing of JS is divided into two stages: pre-compilation and execution period.

    • During precompilation: 代码块 all declared variables and functions in this class are processed (similar to the C language compilation), but note that 1. At this point the handler is only 声明式函数 2. The variable is simply declared but not initialized and assigned

    • Compile the code block from top to bottom during compilation.

Next, we'll take a look at the 1th (block of code) and the 2nd (function) respectively.
f();  // 我是函数声明2function f() {  console.log('我是函数声明1');}function f() {  console.log('我是函数声明2');}

Conclusion 1: In the case of a function declaration, the rule from behind is not changed.

f();  // 我是函数声明function f() {  console.log('我是函数声明');}var f = function() {  console.log('我是赋值型函数');}

Conclusion 2: The function declaration is ahead of the assignment function.

console.log(a);var a; // undefinedconsole.log(b); // 程序直接报错,不往下进行

A is declared below the function, which is advanced (promoted). There is no declaration under Function B (not previously), direct error.
Conclusion 3: The variable declaration is in the pre-compilation stage. proves the correctness of our above.

<script>  f();</script><script>  function f(){};</script>

Conclusion The 4:JS engine is executed in the order of the code blocks. There is no way to preprocess code that has not yet been loaded. This is where the core of the compilation is.

console.log(f);  // Functionfunction f() {  console.log(1);}var f = 3;

Conclusion 5: Function declaration promotion priority is greater than variable declaration, function declaration overrides variable declaration

<script>  console.log(a);</script><script>  console.log(3);</script>

Conclusion 6: If there is an error between code blocks, the other code blocks will execute correctly if they are correct.

Four. War!!! Five is summary and collation, do not want to see the topic can jump directly to five. Code One:
f();var scope = 'out';function f() {  console.log(scope);  var scope = 'in';  console.log(scope);}
    • Variable overrides, which later define the declaration will overwrite the previous.
    • Inside the function: Declare the variable first.

Actual running process:

var scope = 'out';function f() {  var scope;    // 覆盖了外部的。  console.log(scope);  scope = 'in';  console.log(scope);}f();
Code two:
var getName = function(){  console.log(2);}function getName (){  console.log(1);}getName();

It's easy to read the previous words in this question:

    • The function declaration is placed in the pre-compilation stage.
    • The later will cover the front.
      Actual Running Process
function getName (){  console.log(1);}var getName = function(){  console.log(2);}getName();  // 2
Code Three:
getName();     // 1function getName() {  console.log(1);}var getName = function() {  console.log(2);}

It's still easy, don't explain. Variable assignment comes too slowly, unlike a tornado.

Five. Summary and collation

JS is executed in the following order:

    • 1. Read in the first block of code
    • 2. Do grammatical analysis, error is reported grammatical errors, and jump to 5
    • 3. Pre-compile var variables and function (never error, because only parse correct)
    • 4. Execute code block, error is wrong
    • 5. If there is a next block of code, read the next code side, repeat 2
    • 6. End
Six. Did you think that there was no mention of variable elevation? This is actually a black dragon of JS. Before ES, JS has no variable scope. Only function scopes and global scopes.
{  var a = 3;}console.log(a); // 3

After using the Let of ES6, {} a variable scope is inside.

{  let a = 3;}console.log(a); // error

The variable is lifted.

JS execution Order-function declaration promotion, anonymous function, function expression

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.