为什么a未定义而b在var a = b = 3时为3? [英] Why a is undefined while b is 3 in var a=b=3?
问题描述
在以下代码中,我预计 a
和 b
将 3
。但是, a
是 undefined
而 b
是 3
。为什么?
In the following code, I expected both a
and b
to be 3
. However, a
is undefined
and b
is 3
. Why?
(function(){
var a = b = 3;
})();
console.log(typeof a);//"undefined"
console.log(b);//3
推荐答案
这里的问题是大多数开发人员都理解语句 var a = b = 3;
是简写:
The issue here is that most developers understand the statement var a = b = 3;
to be shorthand for:
var b = 3;
var a = b;
但事实上,var a = b = 3;实际上是简写:
But in fact, var a = b = 3; is actually shorthand for:
b = 3;
var a = b;
因此,b最终成为一个全局变量(因为它前面没有var关键字)和即使在封闭函数之外,它仍然在范围内。
Therefore, b ends up being a global variable (since it is not preceded by the var keyword) and is still in scope even outside of the enclosing function.
a未定义的原因是a是该自执行匿名函数的局部变量
The reason a is undefined is that a is a local variable to that self-executing anonymous function
(function(){
var a = b = 3;
})();
这篇关于为什么a未定义而b在var a = b = 3时为3?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!