Last active
September 30, 2023 03:14
-
-
Save awinogradov/92a279ff22b01224a4d2321da7f9e206 to your computer and use it in GitHub Desktop.
Classes
This file contains 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
class Bem { | |
} | |
// src/common/Block/Block.js | |
class Block extends Bem { | |
constructor() { | |
super(); | |
this.a = 1; | |
} | |
tag() { | |
return 'a'; | |
} | |
} | |
// src/common/Block/_mod/Block_mod_val1.js | |
class BlockModVal1Common extends Bem { | |
constructor() { | |
super(); | |
console.log(this.a); // 1 | |
} | |
tag() { | |
return 'b'; | |
} | |
} | |
// src/desktop/Block/_mod/Block_mod_val1.js | |
class BlockModVal1Desktop extends BlockModVal1Common { | |
constructor() { | |
super(); | |
this.a += 1; | |
console.log(this.a); // 2 | |
} | |
tag() { | |
return 'bb'; | |
} | |
} | |
// src/common/Block/_mod/Block_mod_val2.js | |
class BlockModVal2Common extends Bem { | |
constructor() { | |
super(); | |
this.a += 1; | |
console.log(this.a); // 2 or 3 | |
} | |
tag() { | |
return 'c' + super.tag(); // ca or cbb | |
} | |
} | |
// ЭТО ВОТ МУТАБЕЛЬНО! ЛОМАЕТ СУЩЕСТВУЮЩИЕ ПРОТОТИПЫ! | |
function inherits(Inherited, Super) { | |
Inherited.super_ = Super; | |
Object.setPrototypeOf(Inherited.prototype, Super.prototype); | |
return Object.setPrototypeOf(Inherited, Super); | |
} | |
const compose = (...mixins) => { | |
const Base = mixins.splice(0, 1)[0]; | |
return mixins.reduce((Middle, Mixin) => { | |
return inherits(Mixin, Middle); | |
}, Base); | |
} | |
const Res4 = compose(Block, BlockModVal1Desktop, BlockModVal2Common); | |
const Res5 = compose(Block, BlockModVal1Desktop); | |
// const Res6 = compose(Block, BlockModVal1Common, BlockModVal2Common); | |
const inst4 = new Res4(); | |
console.log('Composed: A, BB, C', inst4.tag(), inst4.a); // cbb, 3 | |
const inst5 = new Res5(); | |
console.log('Composed: A, BB', inst5.tag(), inst5.a); // bb, 2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment