Object.create( parentObject{ nestedObject:{} } )

Object.create( parentObject{ nestedObject:{} } )

关于 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

干杯

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");
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
}