Why doesn't the outer scope variable get properly bound to the inner variable?

前端 未结 4 2019
我在风中等你
我在风中等你 2020-12-21 12:12
(function(){
  var x = 23;
  return function(){
    var x = x;
    return x;
  }
}())();

Why does it return undefined instead of 23?

Shou

4条回答
  •  悲哀的现实
    2020-12-21 12:24

    there is a concept called variable hoisting.. i.e in short, just before executing the function, all variables that are declared inside function will be marked undefined. so it returns undefined.. Because of variable hoisting, you can define variable later but can use it before.. eg. function(){alert(x);var x;} will alert undefined but where as function(){alert(x);} throws error..

提交回复
热议问题