Javascript Js es6类构造函数在构造函数实例化之前运行
我有一个es6类,用于实例化函数调用中的变量,但问题是函数似乎是在构造函数实例化并抛出错误之前运行的:Javascript Js es6类构造函数在构造函数实例化之前运行,javascript,ecmascript-6,babeljs,Javascript,Ecmascript 6,Babeljs,我有一个es6类,用于实例化函数调用中的变量,但问题是函数似乎是在构造函数实例化并抛出错误之前运行的: constructor() { this.userSelections = { types : this.getTypes(), providers: this.getProvider() } } getProvider() { // here its throw error that this.userSelections
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或巴别塔无关。以下是问题的简化版本:
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
接受类型
作为参数,可能类似于:
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);
}
}
他的
此
引用用户选择
对象。他正在调用userSelections
对象上的getProviders
。@DanPantry:没有。对象文字不是这样工作的,我错了。我不知道为什么,但我忘记了构造函数创建了一个执行上下文。但是为什么这一行使用this.userSelections.providers=this.getProviders()@user233232:因为现在调用this.getProvider
时,this.userSelection
已经存在。我们在前面的语句中创建了它:this.userSelections={types:this.getTypes()}代码>