Skip to content

Instantly share code, notes, and snippets.

@krimple
Created September 16, 2016 19:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save krimple/5e253d96c2de964192b69f0d50234e65 to your computer and use it in GitHub Desktop.
Save krimple/5e253d96c2de964192b69f0d50234e65 to your computer and use it in GitHub Desktop.
Object.create isn't a direct clone - it's a prototype assignment
class Foo {
constructor(public bar: string) { }
}
let f1 = new Foo('demovalue');
let f2 = Object.create(f1);
console.log(`f1 = ${JSON.stringify(f1)}`);
console.log(`f2 = ${JSON.stringify(f2)}`);
f1.bar = 'changed';
console.log(`changed f1.bar to "changed"`);
console.log(`f1 = ${JSON.stringify(f1)}`);
console.log(`f2 = ${JSON.stringify(f2)}`);
f2.bar = 'changed f2';
f1.bar = 'changed f1';
console.log(`overwrote f2.bar and then updated f1.bar`);
console.log(`f1 = ${JSON.stringify(f1)}`);
console.log(`f2 = ${JSON.stringify(f2)}`);
console.log('moral of the story - understand Object.create is just setting a prototype');
// after running tsc demo.ts, and then node demo.js
> node demo.js
f1 = {"bar":"demovalue"}
f2 = {} // f2's __proto__ property is f1
changed f1.bar to "changed"
f1 = {"bar":"changed"}
f2 = {} // f2 does not override f1's bar property
overwrote f2.bar and then updated f1.bar
f1 = {"bar":"changed f1"}
f2 = {"bar":"changed f2"} // now we have an overridden bar property in the child
moral of the story - understand Object.create is just setting a prototype, NOT cloning directly.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment