gpt4 book ai didi

javascript - 将对象内的数组字符串化

转载 作者:行者123 更新时间:2023-11-28 04:37:00 25 4
gpt4 key购买 nike

有人可以解释为什么 JSON.stringify 输出与 item1 和 item2 对象不同。

var item1 = {
name: '',
childItems: [],
addChild: function (name) {
var child = Object.create(item1);
child.name = name;
this.childItems.push(child);
}
};

var item2 = {
name: '',
addChild: function (name) {
var child = Object.create(item2);
child.name = name;
if (this.childItems === undefined){
this.childItems = [];
}
this.childItems.push(child);
}
};

字符串化对象

var root = Object.create(item1);
root.name = 'root';
root.addChild('child');
console.log(JSON.stringify(root)); //{"name":"root"}

root = Object.create(item2);
root.name = 'root';
root.addChild('child');
console.log(JSON.stringify(root)); //{"name":"root","childItems":[{"name":"child"}]}

后者是我正在寻找的结果,但我无法弄清楚为什么 item1 不起作用?

最佳答案

关键点在于使用Object.create()

var root = Object.create(item1);

创建一个根对象,其原型(prototype)为 item1。在这种情况下,childItems 是原型(prototype)的一部分。在addChild函数中

addChild: function (name) {
var child = Object.create(item1);
child.name = name;
this.childItems.push(child);
}

由于这是root,并且childItems没有在root中定义,所以在原型(prototype)链中查找。由于 item1 是它的原型(prototype),并且它定义了 childItems,因此您将在其中添加该项目。

item2 也是如此,但有一个异常(exception):在您的 addChild 函数中

if (this.childItems === undefined){
this.childItems = [];
}
this.childItems.push(child);

这一行this.childItems = [];在对象根中创建一个数组childItems,隐藏在使用Object.create(item2)<时设置的原型(prototype)中定义的childItems/。这就是为什么您会在第二个 console.log(root) 中看到添加的项目。

this.childItems === undefined 也给出了 undefined (允许创建数组),因为它不是 item2 中原型(prototype)的一部分。

关于javascript - 将对象内的数组字符串化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44117553/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com