2016-11-10 92 views
0

我工作的一個節點模塊上,我想用ES6類語法風格的一致性,保持,但我發現這個模式,我無法重現:的Javascript ES6類語法模式

const proto = module.exports = function(options) { 
    man.opts = options || {}; 
    function man(sentence) { 
     man.say(sentence); 
    } 

    man.__proto__ = proto; 
    man.age = 29; 
    man.say = function(sentence) { 
     console.log(sentence); 
    }; 
    return man; 
}; 

奇怪這個功能的事情是我可以把它稱爲一個標準的構造函數,並讓他的方法和道具得到一個人,但我也可以稱人爲一個函數,並獲得與稱爲他的方法「說」相同的結果。 基本上man('text')產生man.say('text')的相同效果; 如何使用es6類語法重新創建此模式?

+0

功能甘蔗(句子) 實際上被稱爲男人! –

+3

爲了可維護性,除非你有很好的理由,否則不要這樣做。 – Timo

+0

@GiovanniBruno你可以簡單地編輯你的問題來修正錯誤 – Bergi

回答

1

基本上man('text')產生的man.say('text')

最佳相同的效果不使用該圖案在所有。

如何使用es6類語法重新創建此模式?

你可以做到這一點類似於extending Function

export default class { 
    constructor(options) { 
     const man = sentence => this.say(sentence); 
     Object.setPrototypeOf(man, new.target.prototype); 

     man.opts = options || {}; 
     man.age = 29; 

     return man; 
    } 
    say(sentence) { 
     console.log(sentence); 
    } 
} 
+0

理解,tnx !我會嘗試重構我的Express分支,消除這種可怕的模式,但如果事情變得太難,我會嘗試這種方式 –