如何参数化 class 装饰器函数?

How to parametrize the class decorator function?

我有以下测试代码,是从网上的例子中收集的:

function Dec(target: any) {
  console.log("Dec called with: " + JSON.stringify(target));
}

@Dec
class C {
  public x: number = 0;
  constructor() {
    this.x = 5;
  }
  show() {
    console.log("C.show(): " + this.x);
  }
}

let c = new C();
c.show();

使用 tsc --experimentalDecorators test.ts 编译时我没有收到任何警告或任何问题。但是调用它(使用 node test.js 命令),我得到以下结果:

Dec called with: undefined
C.show(): 5

我认为,装饰器无法正常工作,正如网上大多数示例(针对 typescript 1.5)所显示的那样。

如何正确实现这个装饰器?


生成的 javascript 代码是这样的:

var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
function Dec(target) {
    console.log("Dec called with: " + JSON.stringify(target));
}
var C = (function () {
    function C() {
        this.x = 0;
        this.x = 5;
    }
    C.prototype.show = function () {
        console.log("C.show(): " + this.x);
    };
    return C;
}());
C = __decorate([
    Dec
], C);
var c = new C();
c.show();

来自Documentation

The class decorator is applied to the constructor of the class and can be used to observe, modify, or replace a class definition.

作为 target 传递的参数实际上是 C class 的 构造函数 (而不是实际创建的实例) .显然,尝试 JSON.stringify 函数引用将产生 undefined 作为结果。