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

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

问题描述

我正在阅读学习 Node"这本书,但遇到了一个非常简单的问题,我没有考虑太多: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?

推荐答案

Per ECMA-262 § 12.2VariableStatement(即,var identifier=value)显式不返回任何内容.此外,VariableStatement 是一个声明;语句不返回值,将语句放在表达式会去的地方是无效的.

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.

例如,以下没有任何意义,因为它们在您需要产生价值的表达式的地方放置了语句:

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; }

根据 § 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 在普通代码中隐式地创建了一个 global a(但会在严格模式,因为您不允许在严格模式下隐式创建新的全局变量).

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 REPL prints that.

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

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