问题
In Javascript variables are hoisted to the top of the scope they are declared within.
However in the following code it seems that the variable myvar
is not hoisted.
<html>
<body>
</body>
</html>
<script type="text/javascript">
console.log(typeof myvar);
var myvar = "value";
console.log(typeof myvar);
</script>
The output of the above is:
undefined
string
I expected that the first line would say "string" because myvar
is supposed to be hoisted to above it.
Why isn't this so?
回答1:
Variable declarations are hoisted, the assignments are not.
By using var myvar
anywhere in the function you create a locally scoped variable myvar
, but if you follow it with = something
then the assignment will take place in normal code order.
回答2:
A dupe of this came up, and Quentin's answer is good (as always), but just to spell it out even more:
The way the JavaScript engine actually processes that code is like this:
// Before any step-by-step code
var myvar;
// Now step-by-step starts
console.log(typeof myvar); // undefined since no value has been written to it
myvar = "value";
console.log(typeof myvar); // "value" because that's its value now
That is, this:
var myvar = "value";
... is actually two separate things that happen at two separate times. The variable declaration (the var myvar
part), which happens before any step-by-step code in the scope is run, and the initialization (the myvar = "value"
part; it's really an assignment expression by the time it's processed), which happens where that line is in the code.
来源:https://stackoverflow.com/questions/27770845/variable-not-hoisted