2016-11-03 1 views
0

Die Klasse A und B enthalten die gleiche Adressreferenz für das Konfigurationselement. Wie kann ich sie trennen?Vererbung statisches Element getrennt für jede Klasse

class ConfigModel { 

    public static config = [] 

    public foo() { 
     //Code 
    } 

} 

class A extends ConfigModel { 

} 

class B extends ConfigModel { 

} 
+0

Was möchten Sie, dass sie haben? Trenne sie wie? –

+0

A und B haben das Konfigurationselement. Aber wenn ich etwas zu A.config hinzufügen, sollte B.config es – R3Tech

+1

nicht haben ... dann ist das config static ?? –

Antwort

2

Möglicherweise möchten Sie folgendes versuchen:

class ConfigModel { 
    static get config() { 
    return this._config = this._config || []; 
    } 
} 

class A extends ConfigModel { 
} 

class B extends ConfigModel { 
} 

A.config.push(1); 
B.config.push(2); 

console.log(A.config); // [1] 
console.log(B.config); // [2] 

Alles, was es macht, um die s zu definieren tatic Eigenschaft on-the-fly einmal zum ersten Mal zugegriffen. Ich hoffe es hilft!

+0

das ist genial. Für TypeScript füge ich nur 'private static _config' hinzu und es funktioniert einwandfrei – R3Tech

0

Sie können die statische Anordnung von ConfigModel in neue statische Mitglieder klonen in A und B:

class ConfigModel { 
    public static config = [1, 2]; 
} 

class A extends ConfigModel { 
    public static config = ConfigModel.config.slice(0); 
} 

class B extends ConfigModel { 
    public static config = ConfigModel.config.slice(0); 
} 

console.log(ConfigModel.config); // [1, 2] 
console.log(A.config); // [1, 2] 
console.log(B.config); // [1, 2] 

A.config.push(3); 
console.log(ConfigModel.config); // [1, 2] 
console.log(A.config); // [1, 2, 3] 
console.log(B.config); // [1, 2] 

B.config.pop(); 
console.log(ConfigModel.config); // [1, 2] 
console.log(A.config); // [1, 2, 3] 
console.log(B.config); // [1] 

(code in playground)

+0

Ich möchte nicht auf jeder Klasse das Config-Mitglied hinzufügen. Zum Testen von atm ist das Mitglied öffentlich. In Zukunft wird es privat sein. – R3Tech