Skip to content

Instantly share code, notes, and snippets.

@oscar60310
Created December 18, 2020 03:46
Show Gist options
  • Save oscar60310/7e0e46e3c2d5ed0f173ca72fea738ec2 to your computer and use it in GitHub Desktop.
Save oscar60310/7e0e46e3c2d5ed0f173ca72fea738ec2 to your computer and use it in GitHub Desktop.
Snippet about typescript decorators this binding
const authorize = () => (
target: any,
propertyKey: string,
) => {
let next: any;
const getter = () => next;
const setter = (old: any) => {
next = () => {
return old() +1;
}
};
Object.defineProperty(target, propertyKey, {
get: getter,
set: setter,
configurable: true,
enumerable: true,
});
};
const authorizeP = () => (
target: any,
propertyKey: string,
descriptor: any
) => {
const originalMethod = descriptor.value;
descriptor.value = function() {
return originalMethod.apply(this) + 1;
};
};
class A {
public b =3;
@authorizeP()
@authorizeP()
public m (){
console.log(this.b);
return 1;
}
}
const a = new A();
a.b = 5;
console.log(a.m())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment