我正在尝试学习装饰器,但不确定下面的代码为什么不返回我期望的结果...
我想用字符串值修饰一个类,然后将其分配给该类中具有相同名称的属性。
Person.ts
@course({
id: 'rainbow'
})
export class Person {
id: string;
firstName: string;
lastName: string;
constructor(firstName: string, lastName: string) {
this.firstName = firstName;
this.lastName = lastName;
}
public returnNames() {
console.log('Firstname: '+this.firstName+'. Lastname: '+this.lastName+'. ID: '+this.id);
}
}
export function course(options: { id: string }) {
console.log(options.id);
return (target :any) => {
target.id = options.id;
}
}
main.ts
import { Person } from "./Person";
class Startup {
public static main() {
var test = new Person('Matt','OConnor');
test.returnNames();
}
}
Startup.main();
运行此命令的输出是...
$ node main.js
rainbow
Firstname: Matt. Lastname: OConnor. ID: undefined
为什么未定义ID,而不是“彩虹”?