Skip to content

Commit b72f5fc

Browse files
authored
Create incomplete_alternativePattern.md
1 parent fc2bc0b commit b72f5fc

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
2+
// Each mixin is a traditional ES class
3+
class Jumpable {
4+
jump() {}
5+
}
6+
7+
class Duckable {
8+
duck() {}
9+
}
10+
11+
// Including the base
12+
class Sprite {
13+
x = 0;
14+
y = 0;
15+
}
16+
17+
// Then you create an interface which merges
18+
// the expected mixins with the same name as your base
19+
interface Sprite extends Jumpable, Duckable {}
20+
// Apply the mixins into the base class via
21+
// the JS at runtime
22+
applyMixins(Sprite, [Jumpable, Duckable]);
23+
24+
let player = new Sprite();
25+
player.jump();
26+
console.log(player.x, player.y);
27+
28+
// This can live anywhere in your codebase:
29+
function applyMixins(derivedCtor: any, constructors: any[]) {
30+
constructors.forEach((baseCtor) => {
31+
Object.getOwnPropertyNames(baseCtor.prototype).forEach((name) => {
32+
Object.defineProperty(
33+
derivedCtor.prototype,
34+
name,
35+
Object.getOwnPropertyDescriptor(baseCtor.prototype, name)
36+
);
37+
});
38+
});
39+
}
40+
41+
This pattern relies less on the compiler, and more on your codebase to ensure both runtime and type-system are correctly kept in sync.

0 commit comments

Comments
 (0)