ES2015 non dispone di classi in stile Java con costi integrati per il modello di progettazione desiderato. Tuttavia, ha alcune opzioni che possono essere utili, a seconda esattamente di ciò che stai cercando di realizzare.
Se volete una classe che non può essere costruita, ma la cui sottoclassi può, quindi è possibile utilizzare new.target
:
class Abstract {
constructor() {
if (new.target === Abstract) {
throw new TypeError("Cannot construct Abstract instances directly");
}
}
}
class Derived extends Abstract {
constructor() {
super();
// more Derived-specific stuff here, maybe
}
}
const a = new Abstract(); // new.target is Abstract, so it throws
const b = new Derived(); // new.target is Derived, so no error
Per ulteriori dettagli su new.target
, si consiglia di leggere questo quadro generale di come le classi nel lavoro ES2015: http://www.2ality.com/2015/02/es6-classes-final.html
Se stai specificamente alla ricerca di alcuni metodi che richiedono essere attuate, è possibile verificare che nella costruzione della superclasse così:
class Abstract {
constructor() {
if (this.method === undefined) {
// or maybe test typeof this.method === "function"
throw new TypeError("Must override method");
}
}
}
class Derived1 extends Abstract {}
class Derived2 extends Abstract {
method() {}
}
const a = new Abstract(); // this.method is undefined; error
const b = new Derived1(); // this.method is undefined; error
const c = new Derived2(); // this.method is Derived2.prototype.method; no error
ES6 non modifica il meccanismo di ereditarietà prototipo di base delle versioni JavaScript precedenti. Il concetto di "classe astratta" non ha molto senso in termini JavaScript, sebbene un linguaggio di tipo pre-processore possa certamente implementare una cosa del genere. – Pointy
Dato che javascript non è fortemente tipizzato, le classi astratte non sarebbero utili. – gorgi93
Le classi astratte, insieme a tratti e mixin, sono in attesa ["strawman"] (http://wiki.ecmascript.org/doku.php?id=strawman:strawman) [proposta] (http: //wiki.ecmascript ? .org/doku.php id = Strawman: trait_composition_for_classes). –