簡體   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