打字稿方法装饰器 [英] Typescript Method Decorator
本文介绍了打字稿方法装饰器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有此代码
function changeFunc() {
return function(target: any, title: string, descriptor: PropertyDescriptor) {
descriptor.value = function () {
console.log(this.name);
};
return descriptor;
}
}
class Man {
name: string = "asdsds";
constructor(name: string) {
this.name = name;
}
@changeFunc()
getName() {
console.log("Hello");
}
}
var man = new Man('Manos Serifios');
man.getName();
换句话说,我尝试(与装饰器)进行更改方法
In other words i try (with the decorator) to change the method
getName() {
console.log("Hello");
}
与此
function () {
console.log(this.name);
}
但是this.name被评估为未定义.
but this.name evaluated as undefined.
如果我在控制台上登录"this",则似乎是正确的(实例人).
If i console log the "this" it seems that is the right(instance man).
推荐答案
您在decorator方法中没有特定的 object实例的上下文.参数如下(来自 https://www.typescriptlang.org/docs/handbook/decorators.html ):
You don't have the context of a specific object instance inside the decorator method. The parameters are the following (from https://www.typescriptlang.org/docs/handbook/decorators.html):
是静态成员的类的构造函数,还是实例成员的类的原型.
成员的名字.
成员的属性描述符.
这篇关于打字稿方法装饰器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文