我有一个接收一些参数的类的代码,我每次都将它们分配为对象属性。
class InitAnimation {
constructor(settingsAnimation, settingButton, isHelp, isEnd) {
// Initialized the configuration for main animation.
this.settingsAnimation = settingsAnimation;
this.settingButton = settingButton;
this.yes = null;
this.no = null;
this.isHelp = isHelp;
this.isEnd = isEnd;
this.initConfig();
}
在ES6中有更简洁的方法吗?我可以在其中获取参数键值并将它们作为计算属性名称分配给对象?类似的东西:
class InitAnimation {
constructor(settingsAnimation, settingButton, isHelp, isEnd) {
// Initialized the configuration for main animation.
// I know this doesn't work on 'arguments'
arguments.forEach(key => this[key] = arguments[key]);
this.initConfig();
}
对于这种情况,我无法修改参数的发送方式,因为这意味着改变其他人的代码,而且项目现在有点大。我可以在不改变参数传递方式的情况下以更好的方式做到这一点吗?
答案 0 :(得分:2)
是的,在ES2015 +中,您可以使用Object.assign
和速记属性:
constructor(settingsAnimation, settingButton, isHelp, isEnd) {
// Initialized the configuration for main animation.
Object.assign(this, {settingsAnimation, settingButton, isHelp, isEnd});
this.yes = null;
this.no = null;
this.initConfig();
}
直播示例:
class InitAnimation {
constructor(settingsAnimation, settingButton, isHelp, isEnd) {
// Initialized the configuration for main animation.
Object.assign(this, {settingsAnimation, settingButton, isHelp, isEnd});
this.yes = null;
this.no = null;
this.initConfig();
}
initConfig() {
}
}
const a = new InitAnimation("a", "b", "c", "d");
console.log(a);

答案 1 :(得分:2)
这里有几种选择。
对象文字可用于分配属性。这会导致复制和粘贴参数,以便明确枚举它们,但会产生更稳定的代码和函数签名,可以静态分析:
constructor(foo, bar) {
Object.assign(this, { foo, bar });
...
}
可以根据参数列表处理参数。这导致参数列表被枚举一次,但功能签名松散,无法进行静态分析,容易出现人为错误:
constructor(...args) {
['foo', 'bar']
.forEach((paramName, i) => {
this[paramName] = args[i];
});
}
应该注意的是,这在TypeScript中使用parameter properties有效地解决了,这也是为什么可以选择它而不是vanilla JavaScript的原因之一:
constructor(public foo) {}
是
的语法糖constructor(foo) {
this.foo = foo;
}
答案 2 :(得分:1)
您可以使用此技术检测函数参数的名称:
https://davidwalsh.name/javascript-arguments
因此,您可以将其应用于构造函数,然后使用循环将参数名称与其值(通过索引)匹配,然后将它们应用于对象。
function argumentsToObject( func, args ) {
const argNames = getArgumentNames( func ); //use the code from the above link to do this
const resultObject = {};
argsNames.forEach( ( argName, index ) => {
var argValue = args[index];
resultObject[ argName ] = argValue;
});
}
然后在构造函数中,执行
const argsObject = argumentsToObject( InitAnimation.prototype.constructor, arguments );
//copy all the arguments onto this
Object.assign( this, argsObject );