簡體   English   中英

如何從派生的 class 生成 javascript 基礎 class 實例

[英]How to generate a javascript base class instance from a derived class

我的應用程序在兩個進程之間傳遞共享基 class 的實例,每個進程都從基單獨派生以專門化行為。 在 Process1 中,我有派生 class 的實例,我需要從中生成基本 class 實例以傳遞給 Process2。 以下代碼有效,但似乎應該有一種更通用的方式來處理這種情況。 有關如何重寫 generateBase() 的任何建議,以便在將新屬性添加到基礎時它仍然有效?

// base.js included in Process1 and Process2
class base {
    constructor(attribute1, att2) {
        this._a1 = attribute1;
        this._a2 = att2;
    }
}
// derived1.js included only in Process1
class derived1 extends base {
    constructor(a1, a2, a3) {
        super(a1, a2);
        this._a3 = a3;
    }
    generateBase() {
        // base instance to be passed to Process2
        return new base(this._a1, this._a2);
    }                        
    // Other Process1-specific functionality...
}
// derived2.js included only in Process2
class derived2 extends base {
    constructor(a1, a2, a4) {
        super(a1, a2);
        this._a4 = a4;
    }
    // Other Process2-specific functionality...

在您的示例中, derivedbase的孩子,這意味着您可以使用它,因為它是基礎object

class base {
    constructor(attribute1, att2) {
        this._a1 = attribute1;
        this._a2 = att2;
    }
}
class derived extends base {
    constructor(a1, a2, a3) {
        super(a1, a2);
        this._a3 = a3;
    }
    generateBase() {
        // became useless
        return this;
    }                        
}

這是我提出的通用解決方案。 我在 base 內創建了一個 static 實例,然后使用它遍歷屬性並構建新結構。

class base {
    constructor(attribute1, att2) {
        this._a1 = attribute1;
        this._a2 = att2;
    }
    static baseInstance = new base(1,2);
    generateBase() {
        let props = {};
        const keys = Object.keys(base.baseInstance);
        for (let i = 0; i < keys.length; i++) {
            props[keys[i]] = this[keys[i]];
        }
        return props;
    }       
}
// derived1.js included only in Process1
class derived1 extends base {
    constructor(a1, a2, a3) {
        super(a1, a2);
        this._a3 = a3;
    }
}
// derived2.js included only in Process2
class derived2 extends base {
    constructor(b, a4) {
        super(1,2);
        Object.assign(this, b);
        this._a4 = a4;
    }
    // Other Process2-specific functionality...
}

暫無
暫無

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

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