Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Js es6 class constructor function run before the constructor instantiate [duplicate]

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?

like image 528
user233232 Avatar asked Jul 13 '15 09:07

user233232


1 Answers

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);
  }
}
like image 188
Felix Kling Avatar answered Nov 05 '22 06:11

Felix Kling