Last active
December 11, 2015 18:58
-
-
Save gvn/4644870 to your computer and use it in GitHub Desktop.
Illustrated side effect of modifying children of object properties on prototypes. IMO: Object.create() should have a deep copy option.
This file contains 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
var Person = function () {}; | |
Person.prototype.name = 'Person'; | |
Person.prototype.config = { | |
arms: 2 | |
}; | |
Person.prototype.metadata = { | |
type: 'Person' | |
}; | |
var Pirate = function () {}; | |
Pirate.prototype = Object.create(Person.prototype); | |
Pirate.prototype.name = 'Pirate'; // This doesn't affect instances of Person | |
Pirate.prototype.metadata = { type: 'Pirate' }; // This doesn't affect instances of Person | |
Pirate.prototype.config.arms = 1; // This *affects* instances of Person (Person's prototype is modified) | |
var pirate = new Pirate(); | |
console.log('pirate.name : ' + pirate.name); | |
console.log('pirate.config.arms : ' + pirate.config.arms); | |
console.log('pirate.metadata.type : ' + pirate.metadata.type); | |
var person = new Person(); | |
console.log('person.name : ' + person.name); | |
console.log('person.config.arms : ' + person.config.arms); | |
console.log('person.metadata.type : ' + person.metadata.type); | |
console.log('Person.prototype.config.arms: ' + Person.prototype.config.arms); |
Similar Issue:
var Person = {
name: undefined,
bodyParts: {
arms: 2,
legs: 2,
head: 1
}
};
var bob = Object.create(Person);
bob.bodyParts.arms = 1; // This modifies Person!
console.log(Person.bodyParts.arms);
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
JSFiddle
http://jsfiddle.net/XC9Em/