Created
September 16, 2016 19:03
-
-
Save krimple/5e253d96c2de964192b69f0d50234e65 to your computer and use it in GitHub Desktop.
Object.create isn't a direct clone - it's a prototype assignment
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
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'); |
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
// 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