Last active
December 22, 2018 03:46
-
-
Save mohanramphp/1e06c641cf4d73cd825d15c58f79f19f to your computer and use it in GitHub Desktop.
Class 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
export function logClass(target: Function) { | |
// save a reference to the original constructor | |
const original = target; | |
// a utility function to generate instances of a class | |
function construct(constructor, args) { | |
const c: any = function () { | |
return constructor.apply(this, args); | |
} | |
c.prototype = constructor.prototype; | |
return new c(); | |
} | |
// the new constructor behaviour | |
const f: any = function (...args) { | |
console.log(`New: ${original['name']} is created`); | |
return construct(original, args); | |
} | |
// copy prototype so intanceof operator still works | |
f.prototype = original.prototype; | |
// return new constructor (will override original) | |
return f; | |
} | |
@logClass | |
class Employee { | |
} | |
let emp = new Employee(); | |
console.log('emp instanceof Employee'); | |
console.log(emp instanceof Employee); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment