Created
July 7, 2018 20:46
-
-
Save changhuixu/f045a2290f6bd3e2d6f57044ee8a3e2f to your computer and use it in GitHub Desktop.
This file contains hidden or 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 deco( | |
target: any, | |
propertyKey: string, | |
descriptor: PropertyDescriptor | |
) { | |
console.log(`method "${propertyKey}" decorator: begin`); | |
if (descriptor === undefined) { | |
descriptor = Object.getOwnPropertyDescriptor(target, propertyKey); | |
} | |
const originalMethod = descriptor.value; | |
let i = 0; | |
descriptor.value = function (...args: any[]) { | |
const id = `${propertyKey}_${i++}`; | |
console.log(`${id}: begin`); | |
const result = originalMethod.apply(this, args); | |
console.log(`${id}: end`); | |
return result; | |
}; | |
console.log(`method "${propertyKey}" decorator: end`); | |
return descriptor; | |
} | |
class Person { | |
constructor() { | |
console.log(`Class Constructor: called`); | |
} | |
@deco | |
sayHi() { | |
console.log('\t Hi'); | |
} | |
@deco | |
sayBye() { | |
console.log('\t Bye'); | |
} | |
} | |
function main() { | |
console.log(`Main: Start`); | |
const p1 = new Person(); | |
p1.sayBye(); | |
p1.sayBye(); | |
const p2 = new Person(); | |
p2.sayBye(); | |
p2.sayBye(); | |
} | |
main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment