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

5
  • 1
    lion and bird share the same [[Prototype]]. So, adding a property to traits updates the same animal object. Commented Nov 25, 2019 at 7:26
  • 2
    Are you just after deep copy of an object? Commented Nov 25, 2019 at 7: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") Commented Nov 25, 2019 at 7:30
  • adiga: I was wrong, you're right: it will still return false for lion.hasOwnProperty("legs") Commented Nov 25, 2019 at 7:36
  • medium.com/javascript-in-plain-english/… Commented Nov 9, 2020 at 9:31

2 Answers 2

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
}
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

@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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.