Note that there are some explanatory texts on larger screens.

plurals
  1. POCrockford's Prototypal inheritance - Issues with nested objects
    text
    copied!<p>I've been reading "Javascript: The Good Parts" by Douglas Crockford - and while it's a bit extreme, I'm on board with a lot of what he has to say. </p> <p>In chapter 3, he discusses objects and at one point lays out a pattern (also <a href="http://javascript.crockford.com/prototypal.html" rel="nofollow noreferrer">found here</a>) for simplifying &amp; avoiding some of the confusion/issues that come with the use of the built-in "new" keyword.</p> <pre><code>if (typeof Object.create !== 'function') { Object.create = function (o) { function F() {} F.prototype = o; return new F(); }; } newObject = Object.create(oldObject); </code></pre> <p>So I've tried using this in a project I'm working on, and I noticed an issue when attempting to inherit from objects that are nested. If I overwrite a value of a nested object inherited using this pattern, it overwrites the nested element all the way up the prototype chain.</p> <p>Crockford's example is like the <code>flatObj</code> in the following example, which works well. The behaviour, however, is inconsistent with nested objects:</p> <pre><code>var flatObj = { firstname: "John", lastname: "Doe", age: 23 } var person1 = Object.create(flatObj); var nestObj = { sex: "female", info: { firstname: "Jane", lastname: "Dough", age: 32 } } var person2 = Object.create(nestObj); var nestObj2 = { sex: "male", info: { firstname: "Arnold", lastname: "Schwarzenneger", age: 61 } } var person3 = { sex: "male" } person3.info = Object.create(nestObj2.info); // now change the objects: person1.age = 69; person2.info.age = 96; person3.info.age = 0; // prototypes should not have changed: flatObj.age // 23 nestObj.info.age // 96 ??? nestObj2.info.age // 61 // now delete properties: delete person1.age; delete person2.info.age; delete person3.info.age; // prototypes should not have changed: flatObj.age // 23 nestObj.info.age // undefined ??? nestObj2.info.age // 61 </code></pre> <p>(also on a <a href="http://jsfiddle.net/tM7R7/" rel="nofollow noreferrer">fiddle</a>)</p> <p>Am I doing something wrong, or is this a limitation of this pattern?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload