Skip to content

Instantly share code, notes, and snippets.

@gvn
Last active December 11, 2015 18:58
Show Gist options
  • Save gvn/4644870 to your computer and use it in GitHub Desktop.
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.
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);
@gvn
Copy link
Author

gvn commented Jan 26, 2013

FWIW: The same behavior is also seen using the "new" operator on line 15.

Pirate.prototype = new Person();

@gvn
Copy link
Author

gvn commented Jan 26, 2013

@gvn
Copy link
Author

gvn commented Jan 28, 2013

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