JavaScript 代码技巧:foo.x 的值是什么 [英] JavaScript code trick: What's the value of foo.x
问题描述
我在GitHub前端面试题合集中发现了这个问题:
<块引用>var foo = {n: 1};var bar = foo;foo.x = foo = {n: 2};
问题:foo.x 的值是什么?
答案是undefined
.
我做了一些研究,我明白这个问题是(如果我错了,请纠正我):
var foo = {n: 1};
声明一个对象foo
,它的属性n
等于 1.var bar = foo;
声明一个对象bar
,它引用与foo
相同的对象.foo.x = foo = {n: 2};
我相信它等于foo.x = (foo = {n: 2});
- 然后我得到
foo.x
等于undefined
.但是,bar.x
的值是对象{n:2}
.
如果bar
和foo
指向同一个对象,为什么bar.x
得到一个值而foo.x
是 未定义
吗?foo.x = foo = {n: 2};
到底发生了什么?
foo.x = foo = {n: 2};
确定foo.x
引用{n: 1}
对象的属性x
,赋值{n:2}
到foo
,并将foo
的新值——{n:2}
——赋给属性{n: 1}
对象的 x.
重要的是foo.x
所指的foo
是在foo
改变之前确定的.
请参阅 ES5 规范的第 11.13.1 节:
<块引用>让 lref 成为评估 LeftHandSideExpression 的结果.
让 rref 成为评估 AssignmentExpression 的结果.
赋值运算符从右到左关联,所以你得到:
foo.x = (foo = {n: 2})
左侧先于右侧求值.
I found this problem in a GitHub front-end interview questions collection:
var foo = {n: 1}; var bar = foo; foo.x = foo = {n: 2};
Question: What is the value of foo.x?
The answer is undefined
.
I've done some research and what I understand this problem is (correct me if I'm wrong):
var foo = {n: 1};
declares an objectfoo
which has propertyn
equal to 1.var bar = foo;
declares an objectbar
which refers to the same object asfoo
.foo.x = foo = {n: 2};
which I believe is equal tofoo.x = (foo = {n: 2});
- And then I got
foo.x
equals toundefined
. However, the value ofbar.x
is the object{n:2}
.
If bar
and foo
refer to same object, why did bar.x
get a value while foo.x
is undefined
? What is really happening in foo.x = foo = {n: 2};
?
foo.x = foo = {n: 2};
determines that foo.x
refers to a property x
of the {n: 1}
object, assigns {n: 2}
to foo
, and assigns the new value of foo
– {n: 2}
– to the property x
of the {n: 1}
object.
The important thing is that the foo
that foo.x
refers to is determined before foo
changes.
See section 11.13.1 of the ES5 spec:
Let lref be the result of evaluating LeftHandSideExpression.
Let rref be the result of evaluating AssignmentExpression.
The assignment operator associates right to left, so you get:
foo.x = (foo = {n: 2})
The left hand side is evaluated before the right hand side.
这篇关于JavaScript 代码技巧:foo.x 的值是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!