双重分配对象属性会导致未定义的属性

双重分配对象属性会导致未定义的属性

本文介绍了双重分配对象属性会导致未定义的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以说出输出是如何变成undefined的吗?

Can anyone tell how the output became undefined?

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

推荐答案

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

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

The foo.x refers to the property x to the object refered to by foo. However, foo = {n:2} assigns a completely new object to foo. x is indeed assigned to an object, but that object is immediately replaced by another object. The object with the x property isn’t referenced by anything anymore.

您可以将该行读为

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


图形说明

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

这篇关于双重分配对象属性会导致未定义的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 15:00