Skip to content

Instantly share code, notes, and snippets.

@rhalff
Forked from rasmuskl/autobind.ts
Created May 5, 2018 21:30
Show Gist options
  • Save rhalff/5fd1f48bcc38924cfcd6f7acf32d9a0d to your computer and use it in GitHub Desktop.
Save rhalff/5fd1f48bcc38924cfcd6f7acf32d9a0d to your computer and use it in GitHub Desktop.
TypeScript autobind decorator
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