我有一个基类和另一个扩展它的类,我如何访问构造函数中的字段?
class BaseModel {
constructor() {
console.log('no fields :(')
console.log(this.fields)
this.fields.map((field) => {
field.label = field.label || field.name;
})
}
}
class UserModel extends BaseModel {
fields = [
{ name: 'id' },
{ name: 'name' },
{ name: 'email' },
];
constructor(name, email) {
super();
this.name = name;
this.email = email;
}
}
const user = new UserModel('bob', '[email protected]');
console.log(user);
我翻了大约 2 页,但没有找到关于如何设置的令人满意的答案。我发现最好的方法是在构造函数中设置超时,这似乎是错误的。
如果您想在父构造函数同步中访问
fields
,您应该将字段传递给它:
class BaseModel {
constructor(fields) {
this.fields = fields;
console.log(this.fields)
this.fields.map((field) => {
field.label = field.label || field.name;
})
}
}
class UserModel extends BaseModel {
constructor(name, email) {
super([
{ name: 'id' },
{ name: 'name' },
{ name: 'email' },
]);
this.name = name;
this.email = email;
}
}
const user = new UserModel('bob', '[email protected]');
console.log(user);