簡體   English   中英

我有一些 class 的實例,我將它們放入一個數組中。 我可以遍歷數組並更新所有數組對象的價格嗎?

[英]I have some instances of a class and I pushed them into an array. Can I loop through the array and update the price of all the array objects?

我有一個這樣的父構造函數:

let list = [];
class Pictures {
    constructor(price, title) {
        this.price = price;
        this.title = title;
        list.push(this)
    }
    updatePrice(price_increase) {
        this.price = this.price * price_increase / 100 + this.price
        return this.price
    }
}

我還有兩個繼承自 Pictures(Parent) class 的子類

class Photograph extends Pictures {
    constructor(photographer, camera, aperture, contrast, price, title) {
        super(price, title);
        this.price = price;
        this.title = this.title;
        this.photographer = photographer;
        this.camera = camera;
        this.aperture = aperture;
        this.contrast = contrast;
    }
    alterContrast(new_contrast) {
        this.contrast = new_contrast;
    }
    toString() {
        return `Photographer: ${this.photographer}, Camera: ${this.camera},
         Aperture: ${this.aperture}, Contrast: ${this.contrast}`;
    }
}

和:

class Painting extends Pictures {
    constructor(artist, type, owner, title, price) {
        super(price, title);
        this.price = price;
        this.title = title;
        this.artist = artist;
        this.type = type;
        this.owner = owner;
    }
    printProvenance() {

    }
    toString() {
        return `Artist: ${this.artist}, Type: ${this.type}, Owner: ${this.owner}`;
    }
}

這些是類的實例

let photo_one = new Photograph('Kyle', 'Nikon', 32, 21, 30, 'Sunset')

let photo_two = new Photograph("Maya", "Sony XPR", 100, 23, 100.00, "Festival of Color");

我將所有實例推送到父構造函數中的“列表”數組。 是否可以循環遍歷數組,使用Pictures class中的updatePrice方法更新所有對象的價格值?

是的,你可以,只需使用 .map、.forEach 或 for 循環


    list.map((item) => {
        item.updatePrice(1000)
    })

但我可以建議將“列表”存儲在 class 中。

暫無
暫無

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

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