对象属性的双重赋值会导致未定义的属性

时间:2016-06-13 15:17:56

标签: javascript assignment-operator

有人能说出输出如何成为undefined吗?

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

3 个答案:

答案 0 :(得分:7)

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

foo.x引用x引用的对象的属性foo。但是,foo = {n:2}会为foo分配一个全新的对象。确实将x分配给了一个对象,但该对象立即被另一个对象替换。具有x属性的对象不再被任何引用。

您可以将该行读作

foo.x = (foo = {n:2});

图形说明

var foo = {n:2};

First object is assigned to foo

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

foo is reassigned to a second object, but foo.x still points to the first object.

console.log(foo.x);

Trying to access foo.x actually accesses the x property of the second object.

答案 1 :(得分:1)

我将分解每个变量的分配和输出。




  var foo = {n:2}
 #foo:Object {n:2}
 #foo.x:undefined

 foo.x = 3
 #foo:Object {n:2,x:3}&#xA ;#foo.x:3

 foo.x = foo
 #foo:Object {n:2,x:Object {n:2,x:Object(recursive)}}&#xA ; #foo.x:Object {n:2,x:Object {n:2,x:Object(recursive)}}

 foo.x = foo = {n:2}&#xA ;#foo:Object {n:2}
 #foo.x:undefined
  




最后一行,如您所见,将 foo 重置为等于 {n:2} ,这使得 foo.x 不存在(因为你已经覆盖 foo < / code> object)

&#xA;

答案 2 :(得分:0)

您的代码与此代码完全相同,

    var foo = {n:2}; // foo ==> {n:2}
    foo.x = {n:2}; // foo ==> {n:2,x:{n:2}}
    foo = {n:2}; // foo ==> {n:2}
    console.log(foo.x); // undefined 

因为对象中没有“x”键