In JavaScript, what code executes at runtime and what code executes at parsetime?

后端 未结 5 2061
春和景丽
春和景丽 2020-12-12 16:13

With objects especially, I don\'t understand what parts of the object run before initialization, what runs at initialization and what runs sometime after.

EDIT: It s

5条回答
  •  遥遥无期
    2020-12-12 16:16

    A javascript file is run in a 2-pass read. The first pass parses syntax and collects function definitions, and the second pass actually executes the code. This can be seen by noting that the following code works:

    foo();
    
    function foo() {
      return 5;
    }
    

    but the following doesn't

    foo(); // ReferenceError: foo is not defined
    
    foo = function() {
      return 5;
    }
    

    However, this isn't really useful to know, as there isn't any execution in the first pass. You can't make use of this feature to change your logic at all.

提交回复
热议问题