Method Delegation Inheretance
Method Delegation (Prototypal Inheretance or Class Inheretance)
ES6 Class Constructor Version
class Greeter {
constructor (name) {
this.name = name || 'John Doe';
}
hello () {
return `Hello, my name is ${ this.name }`;
}
}
const george = new Greeter('George');
const msg = george.hello();
console.log(msg); // Hello, my name is George
ES5 Constructor Function Version
function Greeter (name) {
this.name = name || 'John Doe';
}
Greeter.prototype.hello = function hello () {
return 'Hello, my name is ' + this.name;
}
var george = new Greeter('George');
var msg = george.hello();
console.log(msg); // Hello, my name is George
Factory Function Version
const proto = {
hello () {
return `Hello, my name is ${ this.name }`;
}
};
const greeter = (name) => Object.assign(Object.create(proto), {
name
});
const george = greeter('george');
const msg = george.hello();
console.log(msg);
Composition Over Class Inheretance
Class inheritance creates is-a relationships with restrictive taxonomies, all of which are eventually wrong for new use-cases. But it turns out, we usually employ inheritance for has-a, uses-a, or can-do relationships.
Composition is more like a guitar effects pedalboard. Want something that can do delay, subtle distortion, and a robot voice? No problem! Just plug them all in:
const effect = compose(delay, distortion, robovoice); // Rock on!
Composition is:
- Simple
- More expressive
- More flexible
Backlinks