【发布时间】: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
干杯
【问题讨论】:
-
lion和bird共享相同的[[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