2016-11-25 85 views
2

我該如何重寫一個ES7類裝飾器的構造函數?用類裝飾器覆蓋構造函數?

例如,我想有這樣的:

@injectAttributes({ foo: 42 }) 
class Bar { 
    constructor() { 
    console.log(this.foo); 
    } 
} 

injectAttributes裝飾將注入到屬性的新實例被創建之前:

> bar = new Bar(); 
42 
> bar.foo 
42 

顯而易見的解決方案 - 使用不同的構造函數:

function overrideConstructor(cls, attrs) { 
    Object.assign(this, attrs); 
    cls.call(this); 
} 

不起作用b ecause創建將成爲新構造的一個實例,而不是原始類型的對象:

> bar = new overrideConstructor(Bar, {foo: 42}) 
42 
> bar 
[overrideConstructor {}] 
> bar instanceof Bar 
false 
+1

ES7中沒有裝飾器。 – Bergi

+0

_「不適用,因爲創建的對象將是新構造函數的實例,而不是原始類型」_沒有「原始類型」。 「酒吧」是裝飾的結果。或者更確切的說,因爲JavaScript中沒有裝飾器。 – zeroflagL

回答

1

的BabelJS REPL不支持的裝飾,所以我現在用的功能(手動和包裝),但概念是相同的。

Here是代碼的工作,以及複製/粘貼以下:

function injectAttributes(cls, attrs) { 
    const injected = function(...args) { 
    Object.assign(this, attrs); 
    return cls.apply(this, args); 
    } 
    injected.prototype = cls.prototype; 
    return injected; 
} 


class BareBar { 
    constructor() { 
    console.log(this.foo); 
    } 
} 
const Bar = injectAttributes(BareBar, { foo: 5 }) 

const thing = new Bar(); 
console.log(thing instanceof Bar); 

此打印:

5 
true 

的裝飾上創建一個新構造,其中屬性注入,然後拷貝原始原型使instanceof工作。

+1

'Uncaught TypeError:類構造函數BareBar不能在沒有'new'的情況下被調用 –