簡體   English   中英

為什么我的子類繼承了基類的 super() 語句中未指定的屬性?

[英]why my subclass inherits property that has not been specified in base-class's super() statement?

在創建產品(父級)class 時,我正在學習 JS OOP:

// Parent Class
class Product {
    constructor (name, categorie, htPrice) {
        this.name = name
        this.categorie = categorie
        this.htPrice = htPrice
    }
}

然后是一個派生的 class:

// Derived Class
class Laptop extends Product {
    constructor (company, store, name, htPrice) {
        super(name, htPrice)
        this.company = company
        this.store = store
    }
}

我指定了我想從基類繼承的屬性,即 (name, htPrice)

super(name, htPrice)

並添加新屬性,即(公司和商店)。 但是,當從派生的 class 向其傳遞一些值並控制台記錄它時,我很驚訝“類別”屬性也被繼承並采用了其中一個值

let item1 = new Laptop('Dell', 'E-bay', 'dell-Latitue', 700)
console.log(item1)
//Laptop {name: 'dell-Latitue', categorie: 700, htPrice: undefined, company: 'Dell', store: 'E-bay'}

我指定了我想從基類繼承的屬性

不,您只需使用兩個 arguments 調用父構造函數 ( super ),盡管它具有三個參數。 通常的 JS function 調用語義適用:第一個參數( name )被賦值為第一個參數( name ),第二個參數( categorie )被賦值為第二個參數( htPrice ),第三個參數( htPrice )被賦值為undefined 並且Product構造函數總是創建三個屬性,沒有if語句或任何東西。

您可能想使用super(name, undefined, htPrice); 反而。 但是,嘗試僅繼承屬性的子集通常是一個有問題的想法 - 在 OOP 中,子類實例具有(必須具有)其基礎 class 的所有屬性和方法。 並且需要能夠在任何地方使用來代替基礎 class 的實例因此,如果Laptop確實沒有類別,那么 inheritance 可能是 model 的錯誤選擇。 或者也許所有筆記本電腦都屬於Laptop類別? 然后寫super(name, 'Laptop', htPrice); .

暫無
暫無

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

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