用于设置实例属性的ES6类构造函数快捷方式

Mon*_*key 6 javascript ecmascript-6

我似乎还记得看到一个捷径,如果属性和构造函数参数被命名为相同的东西,则不必在构造函数中执行this.foo赋值-但我似乎找不到它的引用。

例如:

class Polygon {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
}
Run Code Online (Sandbox Code Playgroud)

你能做些类似的事情吗

class Polygon {
  constructor(height=height, width=width) { 
     // wasn't there a way to declare these arguments so it auto sets the instance variables?
  }
}
Run Code Online (Sandbox Code Playgroud)

Dan*_*ble 12

您可以将其更改为:

class Polygon {
  constructor(height, width) {
    Object.assign(this, { height, width })
  }
}
Run Code Online (Sandbox Code Playgroud)

这意味着您传递的是单个对象而不是多个参数


Ovi*_*lha 5

如果您喜欢这种事情,您可能可以定义一个超类来执行此操作:

class BaseClass {
  constructor(names = [], values = []) {
    names.forEach((n, idx) => this[n] = values[idx]);
  }
}

class Polygon extends BaseClass {
  constructor(height, width) {
    super(['height', 'width'], arguments);
  }
}
Run Code Online (Sandbox Code Playgroud)

当然,是否应该这样做还有很大争议,但这是可能的。请注意,由于可能存在缩小问题,我们不能依赖构造函数中参数名称的名称。