Last active
September 16, 2015 10:30
-
-
Save gr0uch/a599a2ce8db2554a94fd to your computer and use it in GitHub Desktop.
Subclassing without using `class` keyword.
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
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() |
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
// 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