Js es6类构造函数在构造函数实例化之前运行

时间:2015-07-13 09:02:26

标签: javascript ecmascript-6 babeljs

我有一个es6类来实例化一个函数调用的变量,但问题是该函数似乎在构造函数实例化之前运行并抛出错误:

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

  }

问题是什么以及如何处理这种情况?

1 个答案:

答案 0 :(得分:5)

问题与课程,ES6或Babel无关。以下是您问题的简化版本:

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

这会引发错误,因为foo尚未初始化,但此时foo.bar已被访问。

在您的情况下,您在创建要分配给getProvider的对象时调用this.userSelections this.userSelections或其值尚不存在,仍在构建中。

您可以分两步初始化该值:

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

或重构您的代码,以便getProviders接受types作为参数,可能是这样的:

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