jos*_*osh 8 javascript ecmascript-6
我正在阅读有关Babel.js文档的ES6类信息,并注意到它说对象现在可以拥有动态属性名称:
var obj = {
...
// Computed (dynamic) property names
[ "prop_" + (() => 42)() ]: 42
};
Run Code Online (Sandbox Code Playgroud)
这似乎在课堂上也很有用.是否可以在ES6类中执行类似的操作,而无需在构造函数中执行此操作,即:
class Foo {
[ "read" + (...)(['format1', 'format2']) ] {
// my format reading function
}
}
Run Code Online (Sandbox Code Playgroud)
而不是在构造函数中做这样的事情:
class Foo {
constructor(opts) {
let formats = ['format1', 'format2'];
let self = this;
formats.forEach(function(format) {
self["read" + format] = function() {
// my format reading function
}
})
}
}
Run Code Online (Sandbox Code Playgroud)
换句话说,我希望能够获取一些数组,例如['format1', 'format2']并创建两个方法,readformat1并且readformat2在类中动态地不使用构造函数.这可能吗?
是的,有可能,您只错过()了方法签名所需的:
class Foo {
[ "read" + ((format) => format)(myFormat) ]() {
// my format reading function // ^--- this what missed
}
}
Run Code Online (Sandbox Code Playgroud)
巴贝尔代表:这里长而丑陋的网址
截至您更新的问题:这是不可能的(至少我不知道).因此,您可以创建在运行时解析名称的方法,但不能使用该语法从数组创建N方法.
小智 5
我在第一个 Google 链接中发现了这个问题,所以应该给出另一个有用的答案:)
ES6 类主要只是语法糖,因此您仍然可以使用原型并执行类似的操作
class Foo { ... }
let formats = [ 'format1', 'format2' ];
formats.forEach(function(format) {
Foo.prototype['read' + format] = function () { ... }
});
Run Code Online (Sandbox Code Playgroud)
我还没有找到更好的方法。
| 归档时间: |
|
| 查看次数: |
2626 次 |
| 最近记录: |