Reputation: 2105
Get confused.
var message = "Xinrui Ma";
var call = (function(){
message = "I am cool";
})();
alert(message);
From my perspective, the code will be treated like this:
var message = "Xinrui Ma";
var call = (function(){
var message; // it will add message declaration here
message = "I am cool";
})();
alert(message); // this should alert the "Xinrui Ma", not the "I am cool",
// cause Hoisting is JavaScript's default behavior of moving all declarations
// to the top of the current scope
But in fact, it outputs "I am cool", why is that????
Upvotes: 0
Views: 279
Reputation: 478
var
keyword is used to create a local scope, by default it uses the global scope. Hence message here points to global scope and you are modifying it in IIFE.
You can prevent that using
var message = "Xinrui Ma";
var call = (function(){
var message = "I am cool";
})();
alert(message);
Upvotes: 1
Reputation: 781370
If you don't have a variable declaration inside a function, it uses the variable from the containing scope. It doesn't create a new local variable -- there wouldn't be any way to refer to closure variables if it did that.
This has nothing to do with hoisting, which only occurs when you declare the variable in the function. Hoisting would apply if you wrote:
var call = (function() {
message = "I am cool";
var message;
})();
In this case, the var
declaration would be hoisted to the top of the function.
Upvotes: 4