Created
May 7, 2025 14:10
-
-
Save hyrious/5f7df3768566a27be7a0a083d79a2ec8 to your computer and use it in GitHub Desktop.
Ruby's `include` in JavaScript/TypeScript
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 mixin(cls: Function, mod: Function) { | |
const proto = { | |
__proto__: Object.getPrototypeOf(cls.prototype) | |
} | |
Object.getOwnPropertyNames(mod.prototype).forEach(field => { | |
if (field == 'constructor') return; | |
proto[field] = mod.prototype[field] | |
}) | |
Object.setPrototypeOf(cls.prototype, proto) | |
return cls | |
} | |
declare global { | |
interface Function { | |
mixin(mod: Function): this | |
} | |
} | |
Function.prototype.mixin = function (mod: Function) { | |
return mixin(this, mod) | |
} | |
class Mod { | |
foo() { console.log('Mod') } | |
} | |
interface A extends Mod {} | |
class A { | |
static { this.mixin(Mod) } | |
constructor() { | |
this.foo() | |
} | |
} | |
new A() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment