Home > Web Front-end > JS Tutorial > body text

Detailed explanation of js variable promotion and function declaration pre-parsing examples

零下一度
Release: 2017-06-29 09:17:49
Original
1510 people have browsed it

1. First understand the function scope

In JavaScript, the definition of variables is not scoped with the code block, but with the function scope. That is, if a variable is defined within a function, it is not visible outside the function. And if the variable is defined in a code block such as if or for, it is visible outside the code block. In addition, in JavaScript, the term "global variables" refers to variables defined outside all functions, as opposed to "local variables", which refers to variables within a certain function. Among them, the code within the function can access global variables just like accessing its own local variables, but not vice versa.

2. Variable promotion

There is actually a compilation phase before JavaScript code is run. After compilation, it is interpreted and executed from top to bottom, line by line. Variable promotion occurs during the compilation phase, and it promotes the declaration of variables and functions to the top of the scope. (One of the tasks of the compilation phase is to associate variables with their scopes).
So for the code var a =2;, the compiler sees two lines of code var a; a = 2;. The first statement is a declaration statement, which is processed during the compilation phase. The second statement is an assignment statement and is processed during the run phase.

1. The promoted part is only the variable declaration, the assignment statement and executable code logic remain in place
2. The promoted part only promotes the variable declaration to the top of the variable scope where the variable is located, and Not promoted to the global scope
3. Both variable declarations and function declarations will be promoted, but function declarations will be promoted first, followed by variable declarations.
4. For function declarations, if the same function variable declaration is defined, the later-defined declaration will overwrite the previous declaration


The above is the detailed content of Detailed explanation of js variable promotion and function declaration pre-parsing examples. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template