The constructor function of the Js es6 class is executed before the constructor is instantiated

I have an es6 class that creates an instance of a variable from a function call, but the problem is that the function works before creating the constructor instance and throws 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; }); } 

What is the problem and how can I deal with this situation?

+5
source share
1 answer

The problem has nothing to do with ES6 or Babel classes. Here is a simplified version of your problem:

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

This will cause an error because foo is not yet initialized when accessing foo.bar .

In your case, you call getProvider while creating the object you want to assign this.userSelections . this.userSelections or its value does not exist yet, it is still being built.

You can initialize a 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 reorganize your code so that getProviders accepts types as a parameter, perhaps 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); } } 
+5
source

All Articles