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

Javascript 将对象添加到另一个对象中的另一个对象,javascript,extend,Javascript,Extend,假设有三个对象,一个注释、一个注释状态和历史记录: var note = { text: "hello new world" } var history = {} var noteState = {} 如何将note添加到noteState中,然后将noteState添加到历史记录中 我是否可以做一些类似的事情: $.extend(noteState, {"note1": note}); $.extend(history, {"noteState1": noteState}); 如

假设有三个对象,一个注释、一个注释状态和历史记录:

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  // ?

或者有没有其他方法来解决这个问题?谢谢大家!

是的,您可以这样做,而且不必使用extend,只需设置属性即可。您甚至不必使用不同的名称,因此下面的方法就可以了:

noteState.note = note;
history.noteState = noteState;
然后,正如你所写的,你可以使用

 history.noteState.note.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

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

当您使用jQuery的.extend()方法时,实际上是扩展了对象。例如:如果有obj1.text=“object one text”;和obj2.text=“对象两个文本”;,执行$.extend(obj1、obj2)时,obj2的“text”属性将覆盖obj1的。我希望我能解释清楚:)