如何在es6类中动态生成类方法名?

时间:2017-09-13 14:21:57

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

我试图弄清楚是否可以在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 
    })
  }
}

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

我知道可以使用括号表示法创建计算属性,但是我无法弄清楚如何在另一个方法中执行相同的操作。

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

2 个答案:

答案 0 :(得分:0)

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

然而,动态方法是一个非常糟糕的想法......

答案 1 :(得分:-1)

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

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