javascript - What is the execution order of js?
phpcn_u1582
phpcn_u1582 2017-06-26 10:58:23
0
3
676

1. I don’t understand the execution order of js. Execute the following code. When the alert is first started, a has not been declared. Shouldn’t an error be reported directly? Why is this function displayed first, then 10, then 3, and finally an error is reported? Shouldn't an error be reported from the beginning?

alert(a)
a();
var a=3;
function a(){
alert(10)
}
alert(a)
a=6;
a()

phpcn_u1582
phpcn_u1582

reply all(3)
ringa_lee

I asked my classmates and found out why that happened. First of all, we need to understand the concepts
1. In js, variable declarations and function declarations are made in advance, and function declarations are better than variable declarations. Therefore, alert(a) before declaring a will not report an error. Also, in the first alert, the function a appears, not the variable a.
2. The second alert, needless to say, just executes the function a.
3. The third alert, the result is 3, because before running here, var a=3; was executed. So a becomes 3.
4. The last error was reported because a(); a was assigned twice. The first time was var a=3;, and the second time was a=6;, but no matter what, a was assigned It is not a function, so an error is reported.

伊谢尔伦

The first output function is due to hoisting.
The second output 10 is the output of the second line a().
The third output 3 is the output of the third to last line alert(a).
The last error is from the last line a(). Because at this time a has been reassigned to the number 6, which is no longer a function. Of course, an error will be reported when executing a().

某草草

Is the variable declaration promoted? Just remember the following rules.

http://zonxin.github.io/post/...

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template