Skip to content

Instantly share code, notes, and snippets.

@hyrious
Created May 7, 2025 14:10
Show Gist options
  • Save hyrious/5f7df3768566a27be7a0a083d79a2ec8 to your computer and use it in GitHub Desktop.
Save hyrious/5f7df3768566a27be7a0a083d79a2ec8 to your computer and use it in GitHub Desktop.
Ruby's `include` in JavaScript/TypeScript
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