我有点迷失和/或太天真了。我想创建一个带有原型(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
对象必须以特定方式格式化。请参阅此处:
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/