Skip to content

Instantly share code, notes, and snippets.

@mohanramphp
Last active December 22, 2018 03:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mohanramphp/1e06c641cf4d73cd825d15c58f79f19f to your computer and use it in GitHub Desktop.
Save mohanramphp/1e06c641cf4d73cd825d15c58f79f19f to your computer and use it in GitHub Desktop.
Class Decorator
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