Skip to content

Instantly share code, notes, and snippets.

@cspanring
Last active December 19, 2015 18:29
Show Gist options
  • Select an option

  • Save cspanring/5999460 to your computer and use it in GitHub Desktop.

Select an option

Save cspanring/5999460 to your computer and use it in GitHub Desktop.
Prototypal inheritance gotcha in JavaScript - http://mistakes.io/#5999460
// 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