我有以下测试代码,从互联网上的示例中收集:
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
我认为,装饰者不会在路上工作,因为网上的大多数示例(针对打字稿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();
答案 0 :(得分:1)
类装饰器应用于类的构造函数,可以 用于观察,修改或替换类定义。
作为target
传递的参数实际上是C
类的构造函数(而不是创建的实际实例)。显然,尝试JSON.stringify
函数引用会导致undefined
结果。