打字稿方法装饰器

Man*_*ios 6 javascript typescript

我有这个代码

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();  
Run Code Online (Sandbox Code Playgroud)

换句话说,我尝试(使用装饰器)更改方法

getName() {  
    console.log("Hello");  
}  
Run Code Online (Sandbox Code Playgroud)

有了这个

function () {
    console.log(this.name);
}
Run Code Online (Sandbox Code Playgroud)

但 this.name 评估为未定义。

如果我控制台记录“这个”似乎是正确的(例如男人)。

Laj*_*lay 6

您在装饰器方法中没有特定对象实例的上下文。参数如下(来自https://www.typescriptlang.org/docs/handbook/decorators.html):

静态成员的类的构造函数,或实例成员的类的原型

成员的姓名。

成员的属性描述符。