assigment在JavaScript和var关键字 [英] assigment in javascript and the var keyword

查看:124
本文介绍了assigment在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.

这是我们应该认识到,通过节点的REPL,以下内容将返回不确定的作者指出:

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

var a = 2
(undefined)

而code下面将在REPL返回2:

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

a = 2
2

这是为什么?在code正上方是不是归属?怎么来的?如果VARA已不存在,直到code这一点,为什么它是不是和attribuition?

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 attribuition?

推荐答案

ECMA-262 §12.2 ,一个的 VariableStatement 的(即 VAR标识=值)明确返回任何内容。此外,的 VariableStatement 的是一个声明;声明不返回值,它是无效的把一个声明的地方防爆pression会去。

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.

例如,下列任何意义,因为他们把一个声明,你需要的价值收益防爆pressions:

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,分配给一个变量(标识=值)返回分配的值。

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

当你写 VAR一个= 1; ,它声明 A ,并将其值initalizes到 1 。因为这是一个的 VariableStatement 的,它没有返回值,以及REPL版画未定义

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 是一个前pression来分配 1 A 。由于没有 A ,JavaScript的隐含创建的全球 A 在正常code(但会抛出一个的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 之前就存在,前pression仍返回指定的值, 1 ,所以在REPL打印出。

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

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

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