Skip to content

Instantly share code, notes, and snippets.

@sleepyfox
Created April 14, 2022 12:57
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 sleepyfox/bec9da74ed573b1f7c21a5bd7c289266 to your computer and use it in GitHub Desktop.
Save sleepyfox/bec9da74ed573b1f7c21a5bd7c289266 to your computer and use it in GitHub Desktop.
Prototypal inheritance
// 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