Skip to content

Instantly share code, notes, and snippets.

@jkyoutsey
Created June 8, 2016 17:38
Show Gist options
  • Select an option

  • Save jkyoutsey/eb7a52ebed9ed588ab755d4e77f311d5 to your computer and use it in GitHub Desktop.

Select an option

Save jkyoutsey/eb7a52ebed9ed588ab755d4e77f311d5 to your computer and use it in GitHub Desktop.
Angular2 Class Decorator Pattern
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