【问题标题】:How to dynamically generate class method names in an es6 class?如何在 es6 类中动态生成类方法名称?
【发布时间】:2018-02-22 07:29:57
【问题描述】:

我试图弄清楚是否可以在 es6 类上生成方法名称。以下面的例子为例,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')
// ":)"

这样就完成了它应该做的事情,但我还想生成可以像这样工作的便捷方法:

smileyizer.ascii2unicode(':)')

内部调用

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

当然,我也想启用unicode2ascii。 (事实上​​,整件事的重点在于它将与规则集一起使用,其中每个规则可能有十几个键,所以这是很多方便的方法。)

在我的 Replacer 类中,我希望生成类似于以下内容的方法:

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

...然后我会从构造函数中调用它。

我知道使用括号表示法创建计算属性是可能的,但我不知道如何在 another 方法中执行等效操作。

解决方案(感谢@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)
      })
    )
  }

【问题讨论】:

  • somehow create method called firstRule + '2' + secondRule --> 你只需要this[firstRule + '2' + secondRule] = () => { ... } 吗?
  • 哎呀,谢谢詹姆斯。 smiley 应该是 rule。我会解决的。
  • 不要添加问题的答案。这就是答案!
  • 你是在和我说话还是在和 Jeremy 说话?

标签: javascript methods ecmascript-6 es6-class computed-properties


【解决方案1】:
generate(){
  this.rules.map(firstRule =>
    this.rules.map(secondRule => {
       this[firstRule+"2"+secondRule] = char => this.replace(char, firstRule, secondRule);
    });
  );
}

但是,动态方法是一个非常糟糕的主意...

【讨论】:

  • 为什么不好?
  • 感谢您的警告,我会看看情况如何。
【解决方案2】:

在您的构造函数中,您只需要动态创建函数,但您需要这样:

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

【讨论】:

  • 分配一个这样的函数是我所缺少的(我对计算函数想了太多,而简单而明显的答案却让我望而却步。)请参阅更新以获取工作示例。谢谢 Dshook!
猜你喜欢
  • 1970-01-01
  • 2012-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-09
  • 2018-03-21
  • 2018-01-28
相关资源
最近更新 更多