Created
June 8, 2016 17:38
-
-
Save jkyoutsey/eb7a52ebed9ed588ab755d4e77f311d5 to your computer and use it in GitHub Desktop.
Angular2 Class Decorator Pattern
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
| export function MyDecorator(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) { | |
| let c: any = () => { | |
| return constructor.apply(this, args); | |
| }; | |
| c.prototype = constructor.prototype; | |
| return new c(); | |
| } | |
| var f: any = (...args) => { | |
| // the new constructor behavior | |
| // change how you construct before constructing here... | |
| let newInstance = construct(original, args); | |
| // do something with the instance here... | |
| return newInstance; | |
| }; | |
| // copy prototype so intanceof operator still works | |
| f.prototype = original.prototype; | |
| // return new constructor (will override original) | |
| return f; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment