@boost/decorators
Version:
Experimental decorators for common patterns.
36 lines (32 loc) • 1.14 kB
JavaScript
import { isMethod } from './helpers/isMethod.mjs';
/**
* A method decorator that automatically binds a class method's
* `this` context to its current instance.
*/
function Bind() {
return (target, property, descriptor) => {
if (process.env.NODE_ENV !== "production" && (!isMethod(target, property, descriptor) || !('value' in descriptor && typeof descriptor.value === 'function'))) {
throw new TypeError(`\`@Bind\` may only be applied to class methods.`);
}
const func = descriptor.value;
return {
configurable: true,
get() {
const bound = func.bind(this);
// Only cache the bound function when in the deepest sub-class,
// otherwise any `super` calls will overwrite each other.
if (target.constructor.name === this.constructor.name) {
Object.defineProperty(this, property, {
configurable: true,
value: bound,
writable: true
});
}
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return bound;
}
};
};
}
export { Bind };
//# sourceMappingURL=Bind.mjs.map