decorator 运行 我怎么用的时候报错

How decorator run I get a error when I use it

我在我的项目中使用过webpack和babel来使用装饰器,当我这样写时:

class Man{
    constructor(weight = 10, height = 10){
        this.init(weight, height);
    }
    @decorateWeight
    init(w, h){
        this.weight = w;
        this.height = h;
    }
    toString(){
        return `weight: ${this.weight}, height:${this.height}`;
    }
}

function decorateWeight(target, key, descriptor){
    const method = descriptor.value;
    let moreWeight = 100;
    let ret;
    descriptor.value = (...args) => {
        args[0] += moreWeight;
        ret = method.apply(target, args);
        return ret;
    }
    return descriptor
}

它似乎工作正常,但是当我在下面添加这样一行时:

class Man{
    constructor(weight = 10, height = 10){
        this.date = new Date();
        this.init(weight, height);
    }
    @decorateWeight
    init(w, h){
        this.weight = w;
        this.height = h;
        console.log(this.date.getTime());
    }
    toString(){
        return `weight: ${this.weight}, height:${this.height}`;
    }
}

当我新建一个 Man 实例时,我得到了一个错误 "can't call 'getTime' of undefined",我不明白,我哪里出错了?

您的问题是行 method.apply(target, … 和箭头函数的使用。装饰器的targetMan.prototype,不是实例。即使是您的第一个代码片段也没有按照您的想法去做(您可以在实例化多个对象时看到它)。

相反,您应该为该方法使用 function,并在将引用实例的当前 this 值上调用原始 method

function decorateWeight(target, key, descriptor){
    const method = descriptor.value;
    const moreWeight = 100;
    descriptor.value = function (...args) {
        args[0] += moreWeight;
        return method.apply(this, args);
    };
    return descriptor;
}