繁体   English   中英

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

[英]ES6 - Get child class attribute inside parent constructor method

我做了一个抽象类:

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即可轻松开始使用。

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

当我在Promotion类中调用constructor()时,
它无法获取Promotion类的attributes

感谢任何帮助。

这里有很多错误。

这是语法错误:

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

您不能只在类上定义属性。 您需要使用类似this.attributes = ['attribute']类的this.attributes = ['attribute']constructor定义属性。 由于基类构造函数调用_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) 

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM