繁体   English   中英

将对象添加到另一个对象中的另一个对象中

[英]adding an object into another object that is in another object

假设有三个对象,一个音符,一个音符状态和历史记录:

var note = {
    text: "hello new world"
}

var history = {}
var noteState = {}

如何将note添加到noteState中,然后将noteState添加到历史记录中?

我可能做的事情如下:

$.extend(noteState, {"note1": note});
$.extend(history, {"noteState1": noteState});

如果我要回过头来从笔记中获取文字,我该怎么做呢?

history.noteState1.note1.text  // ?

还是有另一种方法可以解决这个问题? 谢谢!

你为什么不简单

var note = {
    text: "hello new world"
}

var history = {}
var noteState = {}

noteState.note = note;
history.noteState= noteState;
alert(history.noteState.note.text);//alerts hello new world

是的,您可以这样做,而不必使用扩展,只需设置属性即可。 您甚至不必使用不同的名称,因此执行以下操作就可以了:

noteState.note = note;
history.noteState = noteState;

然后,就像你写的那样,你可以使用

 history.noteState.note.text

检索嵌套属性。

我想你也可以使用prototype属性来链接你的对象

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM