Skip to content

Instantly share code, notes, and snippets.

@gr0uch
Last active September 16, 2015 10:30
Show Gist options
  • Save gr0uch/a599a2ce8db2554a94fd to your computer and use it in GitHub Desktop.
Save gr0uch/a599a2ce8db2554a94fd to your computer and use it in GitHub Desktop.
Subclassing without using `class` keyword.
const mixins = {
mixinMethod () {
console.log(`This is a mixin method.`)
return this
}
}
// Constructor definitions.
function Class () { console.log(`This is the constructor.`) }
function Subclass () { Class.apply(this, arguments) }
Subclass.prototype = Object.assign(Object.create(Class.prototype), {
subclassMethod () {
console.log(`This is a method on the subclass.`)
return this
}
}, mixins)
new Subclass().subclassMethod().mixinMethod()
// Compared to the ES6 class version:
class Class {
constructor () { console.log(`This is the constructor.`) }
}
class Subclass extends Class {
subclassMethod () { console.log(`This is a method on the subclass.`) }
}
// There is not really mixin support when using `extends`, so it's not really
// a fair comparison.
new Subclass().subclassMethod()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment