[英]How to dynamically generate class method names in an es6 class?
I am trying to figure out if it's possible to generate method names on an es6 class. 我试图找出是否有可能在es6类上生成方法名称。 Take for example the following example, a
Replacer
, which runs replacement rules from a ruleset: 以以下示例为例,一个
Replacer
,它从规则Replacer
运行替换规则:
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')
// ":)"
So that does what it's supposed to, but I would also like to generate convenience methods that would work like this: 这样就可以完成预期的工作,但是我也想生成一种可以这样工作的便捷方法:
smileyizer.ascii2unicode(':)')
which would internally call 在内部调用
smileyizer.replace(':)', 'ascii', 'unicode')
Of course, I would want to enable unicode2ascii
as well. 当然,我也想启用
unicode2ascii
。 (And in fact, the point of this whole thing is that it will be used with rulesets where each rule has perhaps a dozen keys, so that's a lot of convenience methods.) (实际上,整件事的重点是它将与规则集一起使用,其中每个规则可能都有十几个键,因此有很多便捷方法。)
In my Replacer
class, I expect to generate the methods with something akin to: 在我的
Replacer
类中,我期望生成类似于以下内容的方法:
generate(){
this.rules.map(firstRule =>
this.rules.map(secondRule => {
// somehow create method called firstRule + '2' + secondRule
})
}
}
…and then I would call this from the constructor. …然后从构造函数中调用它。
I know it's possible to create computed properties using bracket notation, but I can't figure out how I would do something equivalent from inside another method. 我知道可以使用方括号表示法创建计算属性,但是我无法弄清楚如何从另一个方法中进行等效的操作。
Solution (thanks @DShook) 解决方案(感谢@DShook)
Here's a working generate
method: 这是一个有效的
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)
})
)
}
generate(){
this.rules.map(firstRule =>
this.rules.map(secondRule => {
this[firstRule+"2"+secondRule] = char => this.replace(char, firstRule, secondRule);
});
);
}
However, dynamic methods are a very bad idea... 但是,动态方法是一个非常糟糕的主意...
In your constructor you would just need to dynamically create the functions however you need to like this: 在构造函数中,您只需要动态创建函数即可,但是您需要这样:
this['firstRule' + '2' + 'secondRule'] = function(text, from, to){
return text;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.