以干净的方式从构造函数参数为类设置属性

Jul*_*lla 2 javascript ecmascript-6

我有一个接收一些参数的类的代码,并且每次将它们分配为对象属性一次。

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();
  }
Run Code Online (Sandbox Code Playgroud)

在 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();
}
Run Code Online (Sandbox Code Playgroud)

对于这种情况,我无法修改参数的发送方式,因为这意味着更改其他人的代码,而且该项目现在有点大。我可以在不改变参数传递方式的情况下以更好的方式做到这一点吗?

T.J*_*der 5

是的,在 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();
}
Run Code Online (Sandbox Code Playgroud)

实例:

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();
}
Run Code Online (Sandbox Code Playgroud)