装饰器如何运行我在使用它时遇到错误

时间:2017-02-28 05:29:53

标签: javascript decorator ecmascript-next

我在我的项目中使用了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实例时,我得到一个错误,即“无法调用未定义的'getTime'”,我不明白,我在哪里犯了错误?

1 个答案:

答案 0 :(得分:0)

您的问题是行target和使用箭头功能。装饰器的Man.prototypefunction,而不是实例。即使你的第一个片段也没有做你认为它做的事情(你可以在实例化多个对象时看到它)。

相反,您应该为方法使用method,并在将引用该实例的当前this值上调用原始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; }

hi i am good [anything] hey [another] hii [third] kjkj [fourth]  etc