2015-07-13 19 views
5

Ho un classe ES6 l'un'istanza di una variabile da una chiamata di funzione, ma il problema è che sembra che la funzione sia in esecuzione prima che il costruttore di un'istanza e genera un errore:Js funzione della classe ES6 costruttore eseguire prima del costruttore istanziare

constructor() { 
    this.userSelections = { 
     types : this.getTypes(), 
     providers: this.getProvider() 
    } 
    } 

getProvider() { 
    // here its throw error that this.userSelections is undefined 
    var activeType = this.userSelections.types.some((type) => { 
     return type.active; 
    }); 

    } 

Qual è il problema e come posso gestire questa situazione?

risposta

5

Il problema non ha nulla a che fare con le classi, ES6 o Babele. Ecco una versione semplificata del problema:

var foo = { 
    bar: 42, 
    baz: foo.bar * 2 
}; 

Questo genera un errore perché foo non è ancora inizializzato al momento foo.bar si accede.

Nel tuo caso, si sta chiamando getProviderdurante la creazione dell'oggetto che si desidera assegnare a this.userSelections. this.userSelections o il suo valore non esiste ancora, è ancora in costruzione.

Si potrebbe inizializzare il valore in due fasi:

this.userSelections = { 
    types: this.getTypes() 
}; 
// now that `this.userSelections` exists, we can call `this.getProvider` without problems 
this.userSelections.providers = this.getProvider(); 

o refactoring del codice in modo che getProviders accetta types come parametro, forse qualcosa di simile:

class Foo { 
    constructor() { 
    let types = this.getTypes(); 
    this.userSelection = { 
     types, 
     providers: this._getProvider(types) 
    }; 
    } 

    _getProvider(types) { 
    var activeType = types.some((type) => { 
     return type.active; 
    }); 
    // ... 
    } 

    getProvider() { 
    return this._getProvider(this.userSelection.types); 
    } 
} 
+0

suoi 'this' riferimenti i' userSelections 'oggetto. Sta richiamando 'getProviders' sull'oggetto' userSelections'. –

+2

@DanPantry: No, non è così. Non è così che funzionano gli oggetti letterali. –

+0

Il mio errore. Non so perché, ma ho dimenticato che il costruttore crea un contesto di esecuzione. –

Problemi correlati