问题
I came across this code:
var myVar = 'foo';
(function() {
console.log('Original value was: ' + myVar);
var myVar = 'bar';
console.log('New value is: ' + myVar);
})();
Questions:
- Is IIFE hoisted to the top before global
myVar
? 1a. IF it is, is it executed before globalmyVar
is declared? - In IIFE I get
undefined
first, andbar
second. What is the behind the scenes order of execution in IIFE?
回答1:
- The IIFE is an expression, not a statement, so no it is not hoisted.
var myVar
inside the IIFE is hoisted to the top of the function scope, but the assignment is not. The following is equivalent:
(function(){
var myVar;
console.log('Original value was: '+ myVar);
myVar = 'bar';
console.log('New value is: ' + myVar);
})();
回答2:
Patrick Roberts' answer is excellent, but I wanted to make something clear, there is nothing specific to IIFEs here, all functions work the same, whether they are immediately invoked or not
var myVar = 'foo';
// f1 : creates a variable inside the scope with the same name
function f1 () {
console.log(myVar); // Logs undefined
var myVar = 'hi';
}
// f2 is the same as f1
function f2 () {
var myVar;
console.log(myVar); // Logs undefined
myVar = 'hi';
}
// f3 declares before logging
function f3 () {
var myVar = 'hullo';
console.log(myVar); // Logs the inner value of the variable
}
function logOuterVar () {
console.log(myVar); // Logs the global var
}
f1();
f2();
f3();
logOuterVar();
来源:https://stackoverflow.com/questions/53417054/hoisting-order-with-iife-involved-specific-example