为什么a未定义而b在var a = b = 3时为3? [英] Why a is undefined while b is 3 in var a=b=3?

查看:204
本文介绍了为什么a未定义而b在var a = b = 3时为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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆