-
-
Save rhalff/5fd1f48bcc38924cfcd6f7acf32d9a0d to your computer and use it in GitHub Desktop.
TypeScript autobind decorator
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
function autobind<TFunction extends Function>(constructor: TFunction):TFunction { | |
const newConstructor = function(...args) { | |
constructor.apply(this, args); | |
for (const property in this) { | |
if (typeof this[property] !== typeof Function) { | |
continue; | |
} | |
this[property] = this[property].bind(this); | |
} | |
}; | |
newConstructor.prototype = Object.create(constructor.prototype); | |
newConstructor.prototype.constructor = constructor; | |
return newConstructor as any; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment