2017-06-19 1 views
4

Ich habe eine Klasse wie folgt aus:„new self()“ gleichwertig in Javascript

const Module = { 
    Example: class { 
    constructor(a) { 
     this.a = a; 
    } 

    static fromString(s) { 
     // parsing code 
     return new Module.Example(a); 
    } 
    } 
} 

Das funktioniert so weit, aber die aktuelle Klasse Konstruktor über den globalen Namen Module.Example ist eine Art von hässlich und anfällig Zugriff zu brechen.

In PHP würde ich new self() oder new static() hier verwenden, um auf die Klasse zu verweisen, in der die statische Methode definiert ist. Gibt es in Javascript so etwas, das nicht vom globalen Gültigkeitsbereich abhängt?

+2

Ich würde lernen, wie Prototyp Arbeit zuerst, wie die „Klasse“ Sie erstellen ist bereits ein Objekt. – evolutionxbox

Antwort

6

Sie können einfach this innerhalb der statischen Methode verwenden. Es bezieht sich auf die Klasse selbst statt auf eine Instanz, so dass Sie es von dort aus instanziieren können. Also:

const Module = { 
 
    Example: class Example { 
 
    constructor(a) { 
 
     this.a = a; 
 
    } 
 

 
    static fromString(s) { 
 
     // parsing code 
 
     return new this(s); 
 
    } 
 
    } 
 
} 
 

 
console.log(Module.Example.fromString('my str')) // => { "a": "my str" }