我想知道是否有可能在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)
})
)
}
'不知何故創建方法叫做firstRule +'2'+ secondRule' - >你只需要這個[firstRule +'2'+ secondRule] =() => {...}'? –
哎呀,謝謝詹姆斯。 「笑臉」應該是「規則」。我會解決它。 – pat
不要添加問題的答案。這是一個答案! –