问题
I was trying to understand JavaScript hoisting and from what I have understood, memory space is set aside for all the variable declarations before the execution of the code.
I would like to understand how the interpreter works through hoisting in case of multiple declarations for the same variable. Consider the following code:
console.log(a);
//first declaration
function a() {
console.log('hello');
}
//second declaration
var a = 2;
The output is the function declaration:
function a() {
console.log('hello');
}
So, I am assuming the first declaration the interpreter encounters is the one which is stored in memory. However, changing the order of declarations to:
console.log(a);
//first declaration
var a = 2;
//second declaration
function a() {
console.log('hello');
}
results in the same output! The interpreter ignores the first declaration and stores the second declaration in memory. Why is this happening? Shouldn't the output in the second case be undefined
?
回答1:
Your code will be read by the interpreter like below,
function a() {
console.log('hello');
}
var a;
console.log(a);
a = 2;
so while executing the above code, a
will be referring the function initially and after that var a;
line will be executed, since a
is undefined there, an assigned value will not be set with undefined
by means of a variable declaration. Hence that line got ignored and printing the primitive
value of the function reference.
A simple example for your better understanding would be,
function x(){ };
var x;
console.log(x); //function x(){ }
来源:https://stackoverflow.com/questions/36246543/javascript-hoisting-for-multiple-declarations-of-the-same-variable