Mixiny i klasy,
a idiomatyczny JavaScript
@MichalZalecki
michalzalecki.com
woumedia.com
idiomatyczny
w językoznastwie: właściwy tylko jednemu językowi
‒ sjp.pl
ES2015: Classes
class Person {
constructor(name) {
this.name = name;
}
hi() {
console.log(`Hi ${this.name}!`);
}
by() {
console.log(`By ${this.name}!`);
}
}
const p = new Person("Michal");
p.hi();
p.by();
class Person {
...
}
> Person.prototype
// {
// by: function by(),
// constructor: function Person(name),
// hi: function hi(),
// }
The Two Pillars of JavaScript
- Prototypal Inheritance
- Functional Programming
‒ Eric Elliot
Favor 'object composition' over 'class inheritance'
‒ The Gang of Four
Mixins: extends
const HiMixin = Sup => class extends Sup {
hi() {
console.log(`Hi ${this.name}!`);
}
};
const ByMixin = Sup => class extends Sup {
by() {
console.log(`By ${this.name}!`);
}
};
class Person extends HiMixin(ByMixin(class {})) {
constructor(name) {
super(name);
this.name = name;
}
}
const p = new Person("Michal");
p.hi(); // "Hi Michal!"
p.by(); // "By Michal!"
Mixins: decorators
function hi() { console.log(`Hi ${this.name}!`); }
function by() { console.log(`By ${this.name}!`); }
function mixin(fn, name = fn.name) {
return target => {
target.prototype[name] = fn;
};
}
@mixin(by)
@mixin(hi)
class Person {
constructor(name) {
this.name = name;
}
}
const p = new Person("Michal");
p.hi(); // "Hi Michal!"
p.by(); // "By Michal!"
Class-free OOP is JS's gift to the humanity
‒ Douglas Crockford
Mixins: virtual
function hi() {
console.log(`Hi ${this.name}!`);
}
function by() {
console.log(`By ${this.name}!`);
}
function mixin(fn, name = fn.name) {
return Object.defineProperty(this, name, { value: fn });
}
const p = { name: "Michal" }::mixin(by)::mixin(hi);
p.hi(); // "Hi Michal!"
p.by(); // "By Michal!"
Mixins: stamps
import stampit from "stampit";
function hi() {
console.log(`Hi ${this.name}!`);
}
function by() {
console.log(`By ${this.name}!`);
}
const Person = stampit().methods({ hi, by });
const p = Person({ name: "Michal" });
p.hi(); // "Hi Michal!"
p.by(); // "By Michal!
Mixiny i klasy, a idiomatyczny JavaScript
By Michał Załęcki
Mixiny i klasy, a idiomatyczny JavaScript
- 1,472