2017-02-28 50 views
0

我用的WebPack和巴貝爾在我的項目中使用的裝飾,當我寫像下面這樣:如何裝飾來看,我得到一個錯誤,當我使用它

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}`; 
    } 
} 

當我新的一個人副本,我得到了一個錯誤是「不能調用未定義‘的getTime’」,我不明白,爲什麼我在那裏做一個失誤?

+0

只是這樣的不確定參數它':功能FN2 (... args){return args.reduce(function(x,y){return x + y})}; fn2(1,2,3,4,5); – mfoonirlee

+1

裝飾者**不是** ES7(ES2016)的一部分。這是一個實驗性的功能! –

+0

Thxs提到它。我有點困惑。 – mfoonirlee

回答

0

你的問題是行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; 
} 
+0

謝謝,它的工作原理。我真的很誤解。 – mfoonirlee

相關問題