use*_*232 5 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;
});
}
Run Code Online (Sandbox Code Playgroud)
什么是问题,我怎么能处理这种情况?
这个问题与类,ES6或Babel无关.以下是您的问题的简化版本:
var foo = {
bar: 42,
baz: foo.bar * 2
};
Run Code Online (Sandbox Code Playgroud)
这将抛出一个错误,因为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();
Run Code Online (Sandbox Code Playgroud)
或重构您的代码,以便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);
}
}
Run Code Online (Sandbox Code Playgroud)