Created
February 1, 2017 00:12
-
-
Save XoseLluis/df928f61d5396ac06e4ae5accadaaaf6 to your computer and use it in GitHub Desktop.
Example of Mixin composition and inheritance in ES6
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
function printPrototypeChain(obj){ | |
let protoNames = []; | |
let curProto = Object.getPrototypeOf(obj); | |
while (curProto){ | |
protoNames.push(curProto.constructor.name); | |
curProto = Object.getPrototypeOf(curProto); | |
} | |
console.log("prototype chain:\n" + protoNames.join(".")); | |
} | |
class MySuperClass{ | |
} | |
let Mixin1 = (superclass) => class Mixin1GeneratedSubclass extends(superclass){ | |
method1(){ | |
console.log("method1"); | |
} | |
}; | |
let Mixin2 = (superclass) => class Mixin2GeneratedSubclass extends(superclass){ | |
method2(){ | |
console.log("method2"); | |
} | |
}; | |
function mixinInheritanceTest(){ | |
//Mixin Inheritance. Here I create a new class factory function (Mixin3). It applies other 2 existing mixins to the provided subclass and <strong>adds new methods</strong> to it. For that it's indeed creating an additional class in the prototype chain: ClassA -> Mixin3GeneratedSubclass -> Mixin2GeneratedSubClass -> Mixin1GeneratedSubclass -> superclass</p> | |
let Mixin3 = (superclass) => class Mixin3GeneratedSubclass extends Mixin2(Mixin1(superclass)){ | |
method3(){ | |
console.log("method3"); | |
} | |
}; | |
class ClassA extends Mixin3(MySuperClass){ | |
methodClassA(){ | |
console.log("methodClassA"); | |
} | |
} | |
let a1 = new ClassA(); | |
printPrototypeChain(a1); | |
} | |
function mixinCompositionTest(){ | |
//Mixin Composition. Here I create a new class factory function by combining 2 existing mixins, but it's <strong>not adding new methods</strong> of its own. That's the difference with the previous case, it does not need to add one more class. When used we'll get: ClassA -> Mixin2GeneratedSubClass -> Mixin1GeneratedSubclass -> superclass.</p> | |
let Mixin3 = (superclass) => Mixin2(Mixin1(superclass)); | |
class ClassA extends Mixin3(MySuperClass){ | |
methodClassA(){ | |
console.log("methodClassA"); | |
} | |
} | |
let a1 = new ClassA(); | |
printPrototypeChain(a1); | |
} | |
console.log("- Mixin Inheritance"); | |
mixinInheritanceTest(); | |
console.log("------------------"); | |
console.log("- Mixin Composition"); | |
mixinCompositionTest(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment