ECMAScript 6中较短的类初始化 [英] A shorter class initialisation in ECMAScript 6
问题描述
每次我创建一些课程时,我都需要做同样无聊的过程:
Every time I create some class, I need to do the same boring procedure:
class Something {
constructor(param1, param2, param3, ...) {
this.param1 = param1;
this.param2 = param2;
this.param3 = param3;
...
}
}
有没有办法使其更加优雅和更短?我使用Babel,所以一些ES7实验功能是允许的。可能装修者可以帮助?
Is there any way to make it more elegant and shorter? I use Babel, so some ES7 experimental features are allowed. Maybe decorators can help?
推荐答案
您可以使用 Object.assign
:
You can use Object.assign
:
class Something {
constructor(param1, param2, param3) {
Object.assign(this, {param1, param2, param3});
}
}
这是一个ES2015(又称ES6)功能,一个或多个源对象的目标对象的属性可以枚举。
It's an ES2015 (aka ES6) feature that assigns the own enumerable properties of one or more source objects to a target object.
授予你必须编写参数名称两次,但至少这是一个很短的时间,如果你建立这个作为你的成语,它处理得很好,当你有你想要的实例和其他你没有的参数,例如:
Granted, you have to write the arg names twice, but at least it's a lot shorter, and if you establish this as your idiom, it handles it well when you have arguments you do want on the instance and others you don't, e.g.:
class Something {
constructor(param1, param2, param3) {
Object.assign(this, {param1, param3});
// ...do something with param2, since we're not keeping it as a property...
}
}
Example: (live copy on Babel's REPL):
class Something {
constructor(param1, param2, param3) {
Object.assign(this, {param1, param2, param3});
}
}
let s = new Something('a', 'b', 'c');
console.log(s.param1);
console.log(s.param2);
console.log(s.param3);
输出:
a
b
c
这篇关于ECMAScript 6中较短的类初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!