javascript中的赋值和var关键字 [英] assignment in javascript and the var keyword

查看:175
本文介绍了javascript中的赋值和var关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读学习节点一书,我陷入了一个非常简单的问题,一个我没有过多思考的问题:javascript中的赋值。

I was reading the 'learning Node' book and I was stuck in a very simple issue, one that I haven't given too much thought about: assignment in javascript.

作者声明我们应该意识到通过使用Node的REPL,以下内容将返回undefined:

The author states that we should realize that by using the Node's REPL, the following would return undefined:

var a = 2
(undefined)

,而下面的代码将在REPL中返回'2':

while the code below will return '2' in the REPL:

a = 2
2

为什么?上面的代码不是归属?怎么会?如果var'a'在代码中的那一点之前就不存在了,那怎么会不存在和属性?

why is that? the code right above is not an attribution? how come? If the var 'a' hasn't existed until that point in the code, how come it is not and attribution?

推荐答案

根据 ECMA-262§12.2 VariableStatement (即 var identifier = value )显式不返回任何内容。另外, VariableStatement 是一个Statement;语句不返回值,将Statement放在某个表达式的位置是无效的。

Per ECMA-262 § 12.2, a VariableStatement (that is, var identifier=value) explicitly returns nothing. Additionally, a VariableStatement is a Statement; Statements do not return values, and it is invalid to put a Statement somewhere an Expression would go.

例如,以下任何一个都没有意义,因为它们将Statement放在哪里你需要产生价值的表达式:

For example, none of the following make sense because they put a Statement where you need value-yielding Expressions:

var a = var b;
function fn() { return var x; }

Per §11.13.1赋值到变量( identifier = value )返回指定的值。

Per § 11.13.1, assignment to a variable (identifier=value) returns the assigned value.

当你写 var a = 1时; ,它声明 a 并将其值初始化为 1 。因为这是一个 VariableStatement ,它不返回任何内容,并且REPL打印 undefined

When you write var a = 1;, it declares a and initalizes its value to 1. Because this is a VariableStatement, it returns nothing, and the REPL prints undefined.

a = 1 是一个表达式,它将 1 分配给 a 。由于没有 a ,JavaScript会在正常代码中隐式创建全局 a (但是会在严格模式下抛出 ReferenceError ,因为你不允许在严格模式下隐式创建新的全局变量。)

a=1 is an expression that assigns 1 to a. Since there is no a, JavaScript implicitly creates a global a in normal code (but would throw a ReferenceError in strict mode, since you're not allowed to implicitly create new globals in strict mode).

无论之前是否存在 a ,表达式仍会返回指定的值, 1 ,所以REPL打印出来。

Regardless of whether or not a existed before, the expression still returns the assigned value, 1, so the the REPL prints that.

这篇关于javascript中的赋值和var关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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