簡體   English   中英

如何在js類中聲明一個private成員並將其擴展到其他類?

[英]How to declare a private member in js classes and extend it to other classes?

晚上好。 我想創建一個帶有私有成員#manufacturer 的父類車輛。 我想將類車輛擴展到類汽車和摩托車。 我聲明了 const d = new car。 如果我嘗試通過 console.log(d.manufacturer) 訪問制造商,我收到並未定義。

// task 1

class vehicle {
  #manufacturer;
  name;

  constructor(manufacturer, name) {
    this.#manufacturer = manufacturer;
    this.name = name;
  }

  get name() {
    return this.name;
  }
}

class car extends vehicle {
  #type;
  constructor(manufacturer, name, type) {
    super(manufacturer, name);
    this.#type = type;
  }

  get type() {
    return this.#type;
  }

  set type(value) {
    if (value.length > 3) this.#type = value;
  }
}

class motorcycle extends vehicle {
  motortype;
  constructor(manufacturer, name, motortype) {
    super(manufacturer, name);
    this.motortype = motortype;
  }

  get motortype() {
    return this.motortype;
  }

  set motortype(value) {
    if (value.length > 3) {
      this.motortype = value;
    }
  }
}

const e = new motorcycle('audi', 'a3', 'sport');
console.log(e.motortype);
e.motortype = 'supersport';
console.log(e.motortype);

const d = new car('bmw', 'm2', 'cool');
console.log(d.type);
d.type = 'lazy';
console.log(d.type);
console.log(e.name);
console.log(e.motortype);
console.log(d.manufacturer)

我試圖通過在構造函數中同時放置#manufacturer 來更改構造函數以解決此問題。 但我收到一個錯誤。

私有屬性不會被繼承,因此對於car對象(子類),您無法訪問車輛(超類)中定義的私有成員。 但是您可以使用這樣的公共 get 方法使私有成員可訪問:

 class vehicle { #manufacturer; name; constructor(manufacturer, name) { this.#manufacturer = manufacturer; this.name = name; } get name() { return this.name; } get manufacturer(){ return this.#manufacturer; } } class car extends vehicle { #type; constructor(manufacturer, name, type) { super(manufacturer, name); this.#type = type; } get type() { return this.#type; } set type(value) { if (value.length > 3) this.#type = value; } } class motorcycle extends vehicle { motortype; constructor(manufacturer, name, motortype) { super(manufacturer, name); this.motortype = motortype; } get motortype() { return this.motortype; } set motortype(value) { if (value.length > 3) { this.motortype = value; } } } const e = new motorcycle('audi', 'a3', 'sport'); console.log(e.motortype); e.motortype = 'supersport'; console.log(e.motortype); const d = new car('bmw', 'm2', 'cool'); console.log(d.type); d.type = 'lazy'; console.log(d.type); console.log(e.name); console.log(e.motortype); console.log(d.manufacturer)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM