1

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

Rich
  • 705
  • 9
  • 16
  • 1
    `lion` and `bird` share the same `[[Prototype]]`. So, adding a property to `traits` updates the same animal object. – adiga Nov 25 '19 at 07:26
  • 2
    Are you just after [deep copy of an object](https://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-deep-clone-an-object-in-javascript)? – VLAZ Nov 25 '19 at 07:30
  • 3
    Also, why do you expect `lion.hasOwnProperty("legs")` to return true? Even if you did `lion.traits = { legs: 4 }`, it will still return false for `lion.hasOwnProperty("legs")` – adiga Nov 25 '19 at 07:30
  • adiga: I was wrong, you're right: it will still return false for lion.hasOwnProperty("legs") – Rich Nov 25 '19 at 07:36
  • https://medium.com/javascript-in-plain-english/how-to-deep-copy-objects-and-arrays-in-javascript-7c911359b089 – Rich Nov 09 '20 at 09:31

2 Answers2

1
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");
Suhag Lapani
  • 655
  • 10
  • 18
  • 1
    @Rich Note that, if there are any functions in `animal`, it will removed by `JSON.stringify()`. I think `lion.traits = { legs: 4 }` is a better option – adiga Nov 25 '19 at 07:39
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
}
Singhi John
  • 307
  • 2
  • 10