2015-07-13 28 views
5

Bir ES6 sınıf örneğini bir işlev çağrısından bir değişken var örneğini, ama sorun o yapıcı örneği ve bir hata atmadan işlevi çalıştığını görünüyor geçerli:Js ES6 sınıf yapıcı işlevi

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; 
    }); 

    } 

Sorun nedir ve bu durumu nasıl ele alabilirim?

cevap

5

Sorun, sınıflar, ES6 veya Babel ile ilgisi yoktur. foofoo.bar erişilen şu anda henüz başlatılmadı, çünkü bu bir hata atar

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

: İşte sorunun basitleştirilmiş bir versiyonudur. Senin durumunda

, sen sırasında this.userSelections atamak istediğiniz nesnenin oluşturulmasını getProviderçağrıda bulunuyorlar. this.userSelections veya değeri henüz mevcut değil, hala inşa ediliyor.

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

veya getProviders belki gibi bir şey parametre olarak types kabul böylece kodunuzu refactor:

iki adımda değerini ilklendireceğiniz

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

His 'this' referanslar' userSelections nesne "UserSelections" nesnesine "getProviders" öğesini çağırıyor. –

+2

@DanPantry: Hayır değil. Nesne editörleri böyle çalışmıyor. –

+0

Benim hatam. Neden bilmiyorum ama kurucunun bir yürütme içeriği oluşturduğunu unuttum. –