1

我想知道是否有可能在es6類上生成方法名稱。就拿下面的例子中,一個Replacer,運行替換規則從規則集:如何在es6類中動態生成類方法名?

let smileyRules = [ 
    { ascii: ':)', unicode: ' ' }, 
    { ascii: '8)', unicode: ' ' } 
] 

class Replacer { 
    constructor(rules){ 
    this.rules = rules 
    } 

    replace(text, from, to){ 
    this.rules.forEach(rule => text = text.replace(rule[from], rule[to])) 
    return text 
    } 
} 

let smileyizer = new Replacer(smileyRules) 

smileyizer.replace(':)', 'ascii', 'unicode') 
// " " 

smileyizer.replace(':)', 'unicode', 'ascii') 
// ":)" 

這樣做的事情是應該的,但我也想產生便利的方法,將工作是這樣的:

smileyizer.ascii2unicode(':)') 

這將在內部調用

smileyizer.replace(':)', 'ascii', 'unicode') 

當然,我會想啓用unicode2ascii爲好。 (事實上​​,這整個事情的重點是它將用於每個規則可能有十幾個鍵的規則集,所以這是很多便利方法。)

在我的Replacer類中,我期望生成方法類似於:

generate(){ 
    this.rules.map(firstRule => 
    this.rules.map(secondRule => { 
     // somehow create method called firstRule + '2' + secondRule 
    }) 
    } 
} 

...然後我會從構造函數中調用它。

我知道有可能使用括號表示法創建計算屬性,但我無法弄清楚如何從的另一個方法中執行相同的操作。

解決方案(感謝@DShook)

這裏的工作generate方法:

generate(){ 
    let names = Object.keys(this.rules[0]) 
    names.forEach(firstName => 
     names.forEach(secondName => { 
     let method = firstName + '2' + secondName 
     this[method] = (text, from, to) => this.replace(text, firstName, secondName) 
     }) 
    ) 
    } 
+1

'不知何故創建方法叫做firstRule +'2'+ secondRule' - >你只需要這個[firstRule +'2'+ secondRule] =() => {...}'? –

+0

哎呀,謝謝詹姆斯。 「笑臉」應該是「規則」。我會解決它。 – pat

+0

不要添加問題的答案。這是一個答案! –

回答

0

在構造函數中你只需要動態創建的功能,但是你需要這樣的:

this['firstRule' + '2' + 'secondRule'] = function(text, from, to){ 
    return text; 
} 
+0

指定一個這樣的函數就是我所缺少的(我對計算函數的想法太多了,而簡單明瞭的答案卻讓我無法理解)。謝謝DShook! – pat

1
generate(){ 
    this.rules.map(firstRule => 
    this.rules.map(secondRule => { 
     this[firstRule+"2"+secondRule] = char => this.replace(char, firstRule, secondRule); 
    }); 
); 
} 

然而,動態方法是一個非常糟糕的主意......

+0

他們爲什麼不好? – pat

+0

@pat他們殺了性能。 –

+0

感謝您的警告,我會看看它是如何發生的。 – pat