Javascript 如何在es6类中动态生成类方法名称?
我试图弄清楚是否有可能在es6类上生成方法名。以以下示例为例,Javascript 如何在es6类中动态生成类方法名称?,javascript,methods,ecmascript-6,es6-class,computed-properties,Javascript,Methods,Ecmascript 6,Es6 Class,Computed Properties,我试图弄清楚是否有可能在es6类上生成方法名。以以下示例为例,Replacer,它从规则集运行替换规则: let smileyRules = [ { ascii: ':)', unicode: 'In your constructor you would just need to dynamically create the functions however you need to like this: this['firstRule' + '2' + 'secondRule'] =
Replacer
,它从规则集运行替换规则:
let smileyRules = [
{ ascii: ':)', unicode: '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;
}
让微笑规则=[
{ascii:':)',unicode:'在构造函数中,您只需要动态创建函数,但您需要这样:
generate(){
this.rules.map(firstRule =>
this.rules.map(secondRule => {
this[firstRule+"2"+secondRule] = char => this.replace(char, firstRule, secondRule);
});
);
}
然而,动态方法是一个非常糟糕的主意…以某种方式创建名为firstRule+'2'+secondRule的方法
-->您只需要这个[firstRule+'2'+secondRule]=()=>{…}
?噢,谢谢James。smiley
应该是规则
。我会解决它。不要给问题添加答案。这就是答案!你是在跟我还是杰里米说话?分配这样的函数是我所缺少的(我对计算函数考虑得太多了,而简单明了的答案让我找不到。)请参阅更新以了解一个工作示例。谢谢DShook!为什么它们不好?谢谢警告,我会看看它是如何运行的。