Hoisting order with IIFE involved, specific example

馋奶兔 提交于 2021-01-29 06:31:49

问题


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:

  1. Is IIFE hoisted to the top before global myVar? 1a. IF it is, is it executed before global myVar is declared?
  2. In IIFE I get undefined first, and bar second. What is the behind the scenes order of execution in IIFE?

回答1:


  1. The IIFE is an expression, not a statement, so no it is not hoisted.
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!