问题
There is one sentence in JavaScript Guide about variable scope:"Variables in JavaScript are in a sense "hoisted" or lifted to the top of the function or statement. However, variables that aren't initialized yet will return a value of undefined."
/**
* Example 2
*/
// will return a value of undefined
var myvar = "my value";
(function() {
console.log(myvar); // undefined
var myvar = "local value";
})();
My question is: Why the "console.log(myvar); "will return undefined? I think the first line has initialized myvar a value which is "my value".
回答1:
Because all variable declarations are automatically hoisted to the top of their defining function block, this code:
(function() {
console.log(myvar); // undefined
var myvar = "local value";
})();
is actually this to the JS interpreter:
(function() {
var myvar; // declares a new local variable that covers up the global name
console.log(myvar); // undefined
myvar = "local value";
})();
Which should show you why the locally defined myvar is what console.log() outputs and it has been defined, but not yet initialized so thus it shows as undefined.
The locally defined myvar overrides/covers up the globally defined one so when you access myvar in your function, you only get the locally defined variable (whether it's been initialized yet or not).
See some other references on the same topic:
How do JavaScript variables work?
JavaScript variable undefined vs not defined
One var per function in JavaScript?
JavaScript 'hoisting'
If you remove the var in your function (so you are just referencing a variable, not declaring a new one), then you would only have one global variable named myvar and you would get the behavior it looks like you may be expecting:
var myvar = "my value";
(function() {
console.log(myvar); // outputs "my value"
myvar = "local value";
})();
回答2:
Here your function is a self invoking function. A self-invoking expression is invoked (started) automatically, without being called. Hoisting applies to variable declarations and to function declarations.
var myvar = "my value";
(function() {
console.log(myvar); // undefined
var myvar = "local value";
})();
So here function invoked it self even before initializing myvar with the specified value
来源:https://stackoverflow.com/questions/26291183/javascript-variable-scope-return-undefined