Search code examples
javascriptinheritancepropertiesjavascript-objectsprototypal-inheritance

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


With reference to Sam Elsamman's post, I'm enquiring if you have written a function which gives the expected behaviour to Object.create() please?

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

I expect:

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

Cheers


Solution

  • 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
    }