Class Decorators

  1. function log(prefix?: string) {
  2. return (target) => {
  3. // save a reference to the original constructor
  4. var original = target;
  5. // a utility function to generate instances of a class
  6. function construct(constructor, args) {
  7. var c: any = function () {
  8. return constructor.apply(this, args);
  9. }
  10. c.prototype = constructor.prototype;
  11. return new c();
  12. }
  13. // the new constructor behavior
  14. var f: any = function (...args) {
  15. console.log(prefix + original.name);
  16. return construct(original, args);
  17. }
  18. // copy prototype so instanceof operator still works
  19. f.prototype = original.prototype;
  20. // return new constructor (will override original)
  21. return f;
  22. };
  23. }
  24. @log('hello')
  25. class World {
  26. }
  27. const w = new World(); // outputs "helloWorld"

In the example log is invoked using @, and passed a string as a parameter,@log() returns an anonymous function that is the actual decorator.

The decorator function takes a class, or constructor function (ES5) as anargument. The decorator function then returns a new class constructionfunction that is used whenever World is instantiated.

This decorator does nothing other than log out its given parameter, and itstarget's class name to the console.

原文: https://angular-2-training-book.rangle.io/handout/features/class_decorators.html