Last active
December 19, 2015 18:29
-
-
Save cspanring/5999460 to your computer and use it in GitHub Desktop.
Prototypal inheritance gotcha in JavaScript - http://mistakes.io/#5999460
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Prototypal inheritance gotcha | |
| var myProto = { | |
| prop1: 'foo', | |
| prop2: { | |
| name: 'bar' | |
| } | |
| } | |
| var obj1 = Object.create(myProto); | |
| var obj2 = Object.create(myProto); | |
| // Property mutation only affects instance | |
| obj1.prop1 = 'bar'; | |
| // Array or object mutation affects prototype | |
| obj1.prop2.name = 'foo'; | |
| obj2.prop1; //=> 'foo' | |
| obj2.prop2.name; //=> 'foo' | |
| // Property mutation only affects instance | |
| obj1.prop2 = { name: 'bar' }; | |
| obj1.prop2.name; //=> 'bar' | |
| obj2.prop2.name; //=> 'foo' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment