【问题标题】:Js es6 class constructor function run before the constructor instantiate [duplicate]Js es6类构造函数在构造函数实例化之前运行[重复]
【发布时间】:2015-07-13 09:02:25
【问题描述】:

我有一个 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;
    });

  }

有什么问题,我该如何处理这种情况?

【问题讨论】:

    标签: javascript ecmascript-6 babeljs


    【解决方案1】:

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

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

    这将引发错误,因为在访问 foo.bar 时,foo 尚未初始化。

    在您的情况下,您正在调用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);
      }
    }
    

    【讨论】:

    • 他的this 引用了userSelections 对象。他正在userSelections 对象上调用getProviders
    • @DanPantry:不,它没有。这不是对象字面量的工作方式。
    • 我的错误。我不知道为什么,但我忘记了构造函数创建了一个执行上下文。
    • 但是为什么这条线有效 this.userSelections.providers = this.getProviders();?
    • @user233232:因为现在当this.getProvider被调用时,this.userSelection已经存在。我们在前面的语句中创建了它:this.userSelections = {types: this.getTypes()};
    猜你喜欢
    • 1970-01-01
    • 2016-06-19
    • 1970-01-01
    • 1970-01-01
    • 2016-07-05
    • 2015-12-01
    • 2016-09-16
    • 1970-01-01
    • 2011-05-08
    相关资源
    最近更新 更多