js es6 class 构造函数 运行 在构造函数实例化之前
Js es6 class constructor function run before the constructor instantiate
我有一个 es6 class 从函数调用中实例化一个变量,但问题是函数似乎是 运行 在构造函数实例化并抛出错误之前:
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.bar
时 foo
尚未初始化。
在您的情况下,您在 创建要分配给 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);
}
}
我有一个 es6 class 从函数调用中实例化一个变量,但问题是函数似乎是 运行 在构造函数实例化并抛出错误之前:
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.bar
时 foo
尚未初始化。
在您的情况下,您在 创建要分配给 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);
}
}