gpt4 book ai didi

javascript Object.create 丢失属性

转载 作者:行者123 更新时间:2023-12-01 01:19:03 24 4
gpt4 key购买 nike

我有点迷失和/或太天真了。我想创建一个带有原型(prototype)对象的对象,该对象包含一个函数,该函数将一个值添加到作为属性创建的列表中。

但是Object.create似乎忽略了属性的创建。至少,我是这么想的。

我没有得到什么?

这是一个例子:

const proto = {
add(s) {
this.list.push(s);
}
}
const props = {
list: []
}
const newObj = Object.create(proto, props);

console.log('newObj', newObj);
// What happendened to the list property?

newObj.add('test');
// due to undefined list-Property
// an error is being thrown

最佳答案

问题在于 properties 对象必须以特定方式格式化。请参阅此处:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create#Syntax

These properties correspond to the second argument of Object.defineProperties().

你可以这样做:

const props = {
list: {
value: []
}
}

这是定义属性的最明确的方式,并且有一些 interesting effects 。但除非您需要如此严厉,否则我建议您这样做:

newObj.list = []

关于javascript Object.create 丢失属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54427383/

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