问题
Why does JavaScript hoist variables?
What was the rationale of the designers when they decided to implement hoisting? Are there any other popular languages that do this?
Please provide relevant links to documentation and/or records.
回答1:
As Stoyan Stefanov explains in "JavaScript Patterns" book, the hoisting is result of JavaScript interpreter implementation.
The JS code interpretation performed in two passes. During the first pass, the interpreter processes variable and function declarations.
The second pass is the actual code execution step. The interpreter processes function expressions and undeclared variables.
Thus, we can use the "hoisting" concept to describe such behavior.
回答2:
This is because javascript interpreter interprets code in two cycles.
- Code completion/compilation:
- Code execution:
In 1st cycle all the variable and function declarations are taken to top of the function scope it is executing in. This helps in creating variableObjects
for execution context
of function even before it's execution.
In 2nd phase, value assignments, code statements and function calls takes place line by line in expected manner.
You have a little more detailed read over here.
It will give you a better picture around behavior around let
, const
and class
declarations, also the precedence it follows between variable and functions.
来源:https://stackoverflow.com/questions/15005098/why-does-javascript-hoist-variables