Created
April 14, 2022 12:57
-
-
Save sleepyfox/bec9da74ed573b1f7c21a5bd7c289266 to your computer and use it in GitHub Desktop.
Prototypal inheritance
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
// Prototypal inheritance example | |
// Checked on Node v16.14.2 | |
assert = require('assert') | |
// A cat goes 'meow' | |
class Cat { | |
goes() { | |
return 'meow' | |
} | |
} | |
fluffy = new Cat() | |
assert(fluffy.goes(), 'meow') | |
// So far, so Java | |
// Previous common alternative pattern to ES6 class | |
// for object inheritance - use a prototype object | |
Dog = { | |
goes: function() { | |
return 'woof' | |
} | |
} | |
spot = Object.create(Dog) | |
assert.equal(spot.goes(), 'woof') | |
// Nothing terribly odd up to here | |
// Prototype reassignment | |
// Magic trick, turn fluffy into a dog | |
fluffy.__proto__ = Dog | |
assert.equal(fluffy.goes(), 'woof') | |
// Dynamic augmentation | |
// Magic trick, teach all dogs to sing | |
Dog.sing = () => "We'll... meet again!" | |
// Fluffy can now sing! | |
assert.ok(fluffy.sing().startsWith('We')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment