Created
August 29, 2019 01:54
-
-
Save zebulon988/0282f9f5ce9e3d1e5e22eae0aca7a932 to your computer and use it in GitHub Desktop.
how to create a new constructor which wrap the old
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
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; | |
} |
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
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