I have an es6 class the instantiate a variable from a function call, but the problem is it seems that the function is running before the constructor instantiated and throw an error:
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;
});
}
Whats is the problem and how i can handle this situation?
The problem has nothing to do with classes, ES6 or Babel. Here is a simplified version of your problem:
var foo = {
bar: 42,
baz: foo.bar * 2
};
This will throw an error because foo
is not initialized yet at the moment foo.bar
is accessed.
In your case, you are calling getProvider
during the creation of the object you want to assign to this.userSelections
. this.userSelections
or its value does not exist yet, it is still being constructed.
You could initialize the value in two steps:
this.userSelections = {
types: this.getTypes()
};
// now that `this.userSelections` exists, we can call `this.getProvider` without problems
this.userSelections.providers = this.getProvider();
or refactor your code so that getProviders
accepts types
as parameter, maybe something like:
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With