ES6-在父构造函数方法中获取子类属性

时间:2018-07-30 05:31:25

标签: javascript class ecmascript-6

我做了一个抽象类:

class Model {
  attributes = [];

  constructor(data) {
    this._importAttributes(data);
  }

  _importAttributes(data) {
    this.attributes.forEach((attr) => {
      this[key] = data[attr];
    });
  }
}

,然后从该抽象类进行扩展:

import Model from './model';

class Promotion extends Model {
  attributes = ['id', 'shop_name', 'title', 'description', 'end_time'];

  // No need to state this constructor, just want to state out the problem clearly
  constructor(data) {
    super(data); // <-- Problem occured in here,
    // this.attributes is empty array inside parent constructor
  }
}

这样我就可以像这样使用类:

let promotion = new Promotion({'id': 1, 'shop_name': 'Sample'....});

------我想要实现的目标------

我想在所有扩展子类的_importAttributes()中使用constructor()函数。只需声明子类的attributes即可开始轻松使用。

------遇到问题------

当我在constructor()类中呼叫Promotion时,
它无法获得attributes类的Promotion

感谢您的任何帮助。

2 个答案:

答案 0 :(得分:1)

这里有很多错误。

这是语法错误:

class Model {
  attributes = [];
  // ...
}

您不能只在类上定义属性。您需要使用constructor之类的方法在this.attributes = ['attribute']中定义属性。由于基类构造函数调用_importAttributes,因此您无法先调用super(),然后再将属性添加到子类中,因为您需要先调用super()

您也有this[key] = data[attr];,但未定义key。我认为应该是attr

我认为这样做的一个好方法是将属性作为参数传递给super,默认值为[]。然后,父类可以在调用this.attributes之前将_importAttributes添加到实例。

类似的东西:

class Model {
    constructor(data, attributes=[]) { // accepts attributes
        this.attributes = attributes   // adds them to instance
        this._importAttributes(data);  // now you can use them
    }
  
    _importAttributes(data) {
      this.attributes.forEach((attr) => {
        this[attr] = data[attr];
      });
    }
  }
  
  class Promotion extends Model {
    constructor(data) {
      super(data, ['id', 'shop_name', 'title', 'description', 'end_time']); // pass attributes
    }
  }

let promotion = new Promotion({'id': 1, 'shop_name': 'Sample'})
console.log(promotion)

答案 1 :(得分:0)

截至2018年,ES6类语法尚不支持define class属性。有关更多详细信息,请参见此link。实现所需目标的唯一方法是在构造函数中定义类属性(请参见Mark Meyer的答案)

此外,请注意,ES6中的class关键字只是语法糖,用于创建类似于其他OOP语言的构造函数。它仍然处于早期形式,因此我们需要等待几个版本才能完全支持其他功能。 ES7中有一项建议,允许在class构造中定义属性

相关问题