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

25

我记得曾经看到过一种快捷方式,可以不用在构造函数中进行this.foo赋值,只要属性名和构造函数参数名相同 - 但是我在谷歌上找不到相关的信息了。

例如:

class Polygon {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
}

您是否可以尝试这样做:
class Polygon {
  constructor(height=height, width=width) { 
     // wasn't there a way to declare these arguments so it auto sets the instance variables?
  }
}

16
您可能正在想的是Typescript中的以下内容:http://www.typescriptlang.org/docs/handbook/classes.html#parameter-properties - deceze
1
啊,是的,就是这个 - 所以这是一种仅适用于 TypeScript 而非 ES6 的技巧? - MonkeyBonkey
我不记得 ES 本身有类似的东西。 - deceze
好的 - 是的,那么我想的就是 TypeScript 的特性。继续创建答案,我会接受它的。 - MonkeyBonkey
也许这就是你想要的:https://dev.to/satansdeer/typescript-constructor-shorthand-3ibd - undefined
6个回答

19

你可以将其更改为:

class Polygon {
  constructor(height, width) {
    Object.assign(this, { height, width })
  }
}
这意味着您传递了一个单一的对象,而不是多个参数。

4
如果您对这种事情感兴趣,您可以定义一个超类来完成此操作:
class BaseClass {
  constructor(names = [], values = []) {
    names.forEach((n, idx) => this[n] = values[idx]);
  }
}

class Polygon extends BaseClass {
  constructor(height, width) {
    super(['height', 'width'], arguments);
  }
}

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

2
您可能记得ES6对象字面量简写语法:
function makePolygon(height,width){
    return {height,width}; // in ES5 was return {height:height,width:width};
}

let poly = makePolygon(10,10);
console.log(poly); // {height: 10, width: 10}

另一种解决问题的方法是使用带有配置对象和默认参数的ES6类:
class Polygon{
    constructor(config={}){
        this.name = "Triangle";
        this.height = 10;
        this.width = 10;
        this.numSides = 3;
        Object.assign(this,config);
    }
}

let triangle = new Polygon();
let square = new Polygon({name: "Square", numSides: 4});
let pentagon = new Polygon({name: "Pentagon", numSides:5,height: 20,width: 20});

console.log(triangle,square,pentagon);
// Polygon {name: "Triangle", height: 10, width: 10, numSides: 3}
// Polygon {name: "Square", height: 10, width: 10, numSides: 4}
// Polygon {name: "Pentagon", height: 20, width: 20, numSides: 5}

这对我非常有帮助,我一直在寻找它,非常感谢 :) - Mariusz

1
扩展原型以获得更简明的构造函数。
Object.prototype.initialize = function (obj) { Object.assign(this,obj) }

class Polygon {
  constructor(height,width) {
    this.initialize({height,width})
  }
}

0

使用析构函数如何:

class Polygon {
  constructor({height, width}) { Object.assign(this, arguments[0]); }
}

不过,创建这个对象将需要创建一个“config”对象,视情况而定,可能会使代码变得混乱或更易读:

console.log(new Polygon({height: 100, width: 200}));

将会打印:

Polygon {height: 100, width: 200}

这种方法的一个好处是,如果您从服务器作为json接收多边形对象,则现在可以轻松地将它们恢复到其相应的类:
let dataFromServer = "{\"polygons\":[{\"height\":10,\"width\":20},{\"height\":30,\"width\":40}]}";

console.log(JSON.parse(dataFromServer, (key, value) => {
  if (key === "polygons") return value.map(it => new Polygon(it));
  return value;
}));

0

Object.assign,就像在JavaScript中一样,但在TypeScript中,您应该指定构造函数values是一个object

constructor(values: object) {
    Object.assign(this, values);
}

这里有一个简短的Codepen示例


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接