是否可以在类中拥有多个动态方法名称?

时间:2015-03-09 04:08:41

标签: javascript ecmascript-6

我正在阅读Babel.js's documentation上的ES6类信息,并注意到它说对象现在可以拥有动态属性名称:

var obj = {
    ...

    // Computed (dynamic) property names
    [ "prop_" + (() => 42)() ]: 42
};

这似乎在课堂上也很有用。是否可以在ES6类中执行类似的操作而不在构造函数中执行,即:

class Foo {
  [ "read" + (...)(['format1', 'format2']) ] {
    // my format reading function
  }
}

而不是在构造函数中执行类似的操作:

class Foo {
  constructor(opts) {
    let formats = ['format1', 'format2'];
    let self = this;

    formats.forEach(function(format) {
      self["read" + format] = function() {
        // my format reading function
      }
    })
  }
}

换句话说,我希望能够采用一些数组,例如['format1', 'format2'],并在类中动态创建两个方法readformat1readformat2,而不使用构造函数。这可能吗?

1 个答案:

答案 0 :(得分:5)

是的,有可能,您只错过了方法签名所需的()

class Foo {
  [ "read" + ((format) => format)(myFormat) ]() {
    // my format reading function          // ^--- this what missed
  }
} 

Babel repl:long and ugly url here

截至您更新的问题:这是不可能的(至少我不知道)。因此,您可以创建在运行时解析名称的方法,但不能使用该语法从数组创建N方法。