Skip to content

Instantly share code, notes, and snippets.

@zebulon988
Created August 29, 2019 01:54
Show Gist options
  • Save zebulon988/0282f9f5ce9e3d1e5e22eae0aca7a932 to your computer and use it in GitHub Desktop.
Save zebulon988/0282f9f5ce9e3d1e5e22eae0aca7a932 to your computer and use it in GitHub Desktop.
how to create a new constructor which wrap the old
function logClass(target: any) {
// save a reference to the original constructor
var original = target;
// a utility function to generate instances of a class
function construct(constructor, args) {
var c : any = function () {
return constructor.apply(this, args);
}
c.prototype = constructor.prototype;
return new c();
}
// the new constructor behaviour
var f : any = function (...args) {
console.log("New: " + original.name);
return construct(original, args);
}
// copy prototype so intanceof operator still works
f.prototype = original.prototype;
// return new constructor (will override original)
return f;
}
function classDecorator<T extends {new(...args:any[]):{}}>(constructor:T) {
return class extends constructor {
newProperty = "new property";
hello = "override";
}
}
@classDecorator
class Greeter {
property = "property";
hello: string;
constructor(m: string) {
this.hello = m;
}
}
console.log(new Greeter("world"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment