Class Decorator in Typescript

牧云@^-^@ 提交于 2019-12-23 20:30:23

问题


I'm trying to understand how class decorators work in Typescript when we wish to replace the constructor. I've seen this demo:

const log = <T>(originalConstructor: new(...args: any[]) => T) => {
    function newConstructor(... args) {
        console.log("Arguments: ", args.join(", "));
        new originalConstructor(args);
    }
    newConstructor.prototype = originalConstructor.prototype;
    return newConstructor;
}

@log
class Pet {
    constructor(name: string, age: number) {}
}

new Pet("Azor", 12);
//Arguments: Azor, 12

Everything is understood but this line:

newConstructor.prototype = originalConstructor.prototype;

Why do we do that?


回答1:


The classes like:

class Pet {
    constructor(name: string, age: number) {}
    dosomething() {
        console.log("Something...");
    }
}

Are compiled into functions when targeting ES5:

var Pet = (function () {
    function Pet(name, age) {
    }
    Pet.prototype.dosomething = function () {
        console.log("Something...");
    };
    return Pet;
}());

As you can seem when we use functions to define classes. The methods are added to the function's prototype.

This means that if you are going to create a new constructor (new function) you need to copy all the methods (the prototype) from the old object:

function logClass(target: any) {

  // save a reference to the original constructor
  const original = target;

  // a utility function to generate instances of a class
  function construct(constructor: any, args: any[]) {
    const c: any = function () {
      return constructor.apply(this, args);
    };
    c.prototype = constructor.prototype;
    return new c();
  }

  // the new constructor behaviour
  const newConstructor: any = function (...args: any[]) {
    console.log("New: " + original.name);
    return construct(original, args);
  };

  // copy prototype so intanceof operator still works
  newConstructor.prototype = original.prototype;

  // return new constructor (will override original)
  return newConstructor;
}

You can learn more at "Decorators & metadata reflection in TypeScript: From Novice to Expert (Part I)"

Update

Please refer to https://github.com/remojansen/LearningTypeScript/tree/master/chapters/chapter_08 for a more recent version.



来源:https://stackoverflow.com/questions/44519282/class-decorator-in-typescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!