使用JavaScript进行多项左手分配,真的是正确的关联吗? [英] Multiple left-hand assignment with JavaScript, really right associative?

查看:156
本文介绍了使用JavaScript进行多项左手分配,真的是正确的关联吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这篇文章中,使用JavaScript进行多项左手分配,@ Crescent Fresh说JavsScript的左手任务是正确的。但是下面的代码在我看来它打破了正确的关联性:

In this post, Multiple left-hand assignment with JavaScript, @Crescent Fresh says JavsScript left-hand assignment is right associative. But the following code seems to me it breaks right associativeness:

var a = {n: 1};
a.x = a = {n: 2};
console.log(a.x);// undefined

任何人都可以解释为什么 ax 未定义?

Can anyone explain why a.x is undefined?

编辑:上面的代码段是测试正确的关联性,在现实世界中请不要写类似的代码。

The snippet above is to test "right associativeness", in real world please do not write similar code.

推荐答案

tl; dr - JS计算出值的位置,然后计算出该值是什么,以及一方计算出该值的效果会改变 a 的值。

tl;dr — JS works out where to put the value before working out what that value is, and a side effect of working out what that value is changes the value of a.

请参阅简单分配规范

第1步是让lref成为评估LeftHandSideExpression的结果。

Step 1 is "Let lref be the result of evaluating LeftHandSideExpression."

第2步是让rref是评估AssignmentExpression的结果。

Step 2 is "Let rref be the result of evaluating AssignmentExpression."

所以首先发生的是一个属性 x 是在存储在 a 中的对象(其中n为1)。

So the first thing that happens is that a property x is created on the object stored in a (where n is 1).

然后右边ha评估nd方(最终覆盖 a ,其中n为2的新对象。)

Then the right hand side is evaluated (which ends up overwriting a with a new object where n is 2).

然后该表达式(该对象,其中n为2)的结果被分配给原始对象上的 x (其中n为1)。

Then the result of that expression (that object where n is 2) is assigned to x on the original object (where n is 1).

你可以看到这个效果:

"use strict";
var a = {n: 1};
var b = a;

a.x = a = {n: 2};

console.log(a);
console.log(b);

这篇关于使用JavaScript进行多项左手分配,真的是正确的关联吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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