Why is one variable undefined outside of the IIFE while the other is not?

问题: I was playing with IIFE and I'm confused. The value of a is undefined but b is not. Why am I able to access the value of b outside of IIFE? (function(){ var...

问题:

I was playing with IIFE and I'm confused. The value of a is undefined but b is not. Why am I able to access the value of b outside of IIFE?

(function(){
  var a = b = 3;
})();

console.log("a defined? " + (typeof a !== 'undefined')); // false
console.log("b defined? " + (typeof b !== 'undefined')); // true


回答1:

Declaration syntax can be confusing, because it looks like the syntax for ordinary expressions. It is, however, different.

var a = b = 3;

is parsed as

var a = (something);

In this case, something is b = 3, so it's exactly as if your function looked like

b = 3;
var a = b;

The "naked" b = 3 without var or let or const creates an implicit global variable. Thus b is visible outside the function, while a is not.


回答2:

There are four ways of declaring a variable in JavaScript:

  • var, which will scope that variable to the declaring function.
  • let/const, which will scope that variable to the declaring block.
  • Implicit declaration, which will scope that variable globally (unless previously declared in a different scope, in which case it will reassign that instead).
var a = b = 3;

In this statement, we declare a in the function scope with the value of b = 3. The expression b = 3 has value 3, but implicitly declares the variable b as well, which means that b will be declared in the global scope.

Outside of the function, the variable b is declared (since it was implicitly declared globally) while a is not (since it was declared only in the scope of the function).


You should avoid implicitly declared variables, though (and preferably use let and const instead of var), so the above code should have been written like this:

(function() {
  let a = 3;
  let b = a;
});

Or, if you actually want the variables declared outside of the function as well:

let a, b;
(function() {
  // NOTE: not implicit declaration since a and b are both already declared
  a = 3;
  b = a;
})();
  • 发表于 2019-03-11 05:41
  • 阅读 ( 212 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除