我如何才能1)将原型道具从父构造函数传递给子构造函数,2)使用destructure来组织所有构造函数的参数,而不引起类型错误?
这就是我想修正的代码。
function Participant ({gender, age, tastes, education}){
this.gender = gender;
this.age = age;
this.tastes = tastes || [];
this.education = education || 0;
}
function Payer(gender, age, tastes, education, income, job){
this.base = Participant;
this.base(gender, age, tastes, education);
this.income = income;
this.job = job || 'merchant';
}
Payer.prototype = new Participant;
function NotPayer({gender, age, tastes, role}){
this.role = role || 'kid';
this.base = Participant;
this.job = 'Not Valid';
this.base(gender, age, tastes);
}
NotPayer.prototype = new Payer;
const kid1 = new NotPayer({role: 'nephew', age: 6, gender: 'male', tastes: ['ps4', 'golf']});
kid1.role;// 'nephew'
const kid2 = new Participant({gender: 'female'});
kid2.gender; // Type Error: Cannot destructure property 'gender' of 'undefined'
我试图修复的是这样的:
function Participant ({gender, age, tastes, education}){
this.gender = gender;
this.age = age;
this.tastes = tastes || [];
this.education = education || 0;
}
function Payer(gender, age, tastes, education, income, job){
this.base = Participant;
this.base(gender, age, tastes, education);
this.income = income;
this.job = job || 'merchant';
}
//Payer.prototype = new Participant;
function NotPayer({gender, age, tastes, role}){
this.role = role || 'kid';
this.base = Participant;
this.job = 'Not Valid';
this.base(gender, age, tastes);
}
//NotPayer.prototype = new Payer;
const kid1 = new NotPayer({role: 'nephew', age: 6, gender: 'male', tastes: ['ps4', 'golf']});
console.log(kid1.role); // nephew
const kid2 = new Participant({gender: 'female'});
console.log(kid2.gender); // female
这只是因为我在表达式中添加了注释,将父构造函数分配给子构造函数(结果是,例如: kid1.gender
成为 undefined
)
注意到 这段代码可以同时使用父原型继承和参数析构,但只有在下面的情况下(在最后一个构造子函数中使用析构时)。
function Participant (gender, age, tastes, education){
this.gender = gender;
this.age = age;
this.tastes = tastes || [];
this.education = education || 0;
}
function NotPayer({gender, age, tastes, role}){
this.role = role || 'kid';
this.base = Participant;
this.job = 'Not Valid';
this.base(gender, age, tastes);//check education
}
NotPayer.prototype = new Participant;
const kid1 = new NotPayer({role: 'nephew', age: 6, gender: 'male', tastes: ['ps4', 'golf']});
console.log(kid1.gender); // male
console.log(NotPayer.prototype); // Participant{...}
谢谢!!很抱歉这个问题的范围。
试试这个
class Participant {
constructor(gender, age, tastes, education) {
this.gender = gender;
this.age = age;
this.tastes = tastes || [];
this.education = education || 0;
}
}
class NotPayer extends Participant {
constructor({gender, age, tastes, role}) {
super(gender, age, tastes)
this.role = role || 'kid';
this.job = 'Not Valid';
}
}
const kid1 = new NotPayer({role: 'nephew', age: 6, gender: 'male', tastes: ['ps4', 'golf']});
console.log(kid1.gender)
console.log(NotPayer.prototype)