【问题标题】:Object.create( parentObject{ nestedObject:{} } )Object.create(父对象{嵌套对象:{}})
【发布时间】:2020-03-20 10:52:06
【问题描述】:

关于Sam Elsamman's post,我想知道您是否编写了一个函数,它可以为 Object.create() 提供预期的行为?

var animal = {traits: {}};            // a nested object as parent
var lion = Object.create(animal);
var bird = Object.create(animal);
lion.traits.legs = 4;
bird.traits.legs = 2;

console.log(lion.traits.legs);        // 2

// edited following adiga's comment:`
animal.traits.hasOwnProperty("legs"); // true

我希望:

// edited following adiga's comment:
console.log(lion.traits.legs);        // 4
animal.traits.hasOwnProperty("legs"); // false

干杯

【问题讨论】:

  • lionbird 共享相同的 [[Prototype]]。因此,向traits 添加属性会更新同一个动物对象。
  • 你是在deep copy of an object之后吗?
  • 另外,您为什么期望lion.hasOwnProperty("legs") 返回true?即使你做了lion.traits = { legs: 4 },它仍然会为lion.hasOwnProperty("legs")返回false
  • adiga:我错了,你是对的:它仍然会为 lion.hasOwnProperty("legs") 返回 false

标签: javascript inheritance properties javascript-objects prototypal-inheritance


【解决方案1】:
const create = (proto) => {
  const o = {}
  o.__proto__ = proto
  Object.keys(proto).forEach(key => {
    const val = proto[key]
    if (typeof val === 'object')
       o[key] = Object.assign({}, val)
    else
       o[key] = val
  })
  return o
}

【讨论】:

    【解决方案2】:
    var animal = {traits: {}};            // a nested object as parent
    var lion = Object.create(JSON.parse(JSON.stringify(animal)));
    var bird = Object.create(JSON.parse(JSON.stringify(animal)));
    lion.traits.legs = 4;
    bird.traits.legs = 2;
    
    console.log(lion.traits.legs);        
    lion.hasOwnProperty("legs");         
    animal.traits.hasOwnProperty("legs");
    

    【讨论】:

    • @Rich 请注意,如果animal 中有任何功能,它将被JSON.stringify() 删除。我认为lion.traits = { legs: 4 } 是更好的选择
    猜你喜欢
    • 2019-04-14
    • 2015-03-13
    • 1970-01-01
    • 1970-01-01
    • 2012-11-12
    • 2019-07-22
    • 2018-07-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多