Js es6类的构造函数运行前先实例化构造函数

Js es6 class constructor function run before the constructor instantiate

本文关键字:构造函数 实例化 运行 Js es6      更新时间:2023-09-26

我有一个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;
    });
  }
问题是什么,我该如何处理这种情况?

问题与类、ES6或Babel无关。以下是您的问题的简化版本:

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

这将抛出一个错误,因为foo在访问foo.bar时还没有初始化。

在您的例子中,您在创建您想要分配给this.userSelections的对象期间调用getProvider 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);
  }
}