如何在方法"refactorGroupInfo“中更改构造函数的一个属性,以便其他属性不会”未定义“。或如何使此方法具有通用性,以便您可以更改构造函数的一个属性或所有属性。
class Group {
constructor(nameGroup,course,specialization) {
this.nameGroup = nameGroup;
this.course = course;
this.specialization = specialization;
}
refactorGroupInfo(nameGroup, course,specialization) {
this.nameGroup = nameGroup;
this.course = course;
this.specialization = specialization;
}
}
let Dev = new Group("D-11",4,"Front-end");
Devs.refactorGroupInfo("D-12");
console.log(Devs);
发布于 2018-06-11 12:28:39
我更喜欢使用一个对象,这样你在里面定义的每个键都会被修改。
class Group {
constructor(nameGroup, course, specialization) {
this.nameGroup = nameGroup;
this.course = course;
this.specialization = specialization;
}
refactorGroupInfo(object) {
Object.keys(object).forEach((x) => {
this[x] = object[x];
});
}
}
const dev = new Group('D-11', 4, 'Front-end');
dev.refactorGroupInfo({
nameGroup: 'D-12',
});
console.log(dev);
发布于 2018-06-11 12:24:14
在您的refactorGroupInfo函数中,您可以添加一个检查,以查看该函数的参数是否尚未定义。
refactorGroupInfo(nameGroup, course,specialization) {
this.nameGroup = typeof nameGroup !== 'undefined' ? nameGroup : this.nameGroup;
this.course = typeof course !== 'undefined' ? course : this.course;
this.specialization = typeof specialization !== 'undefined' ? specialization : this.specialization;
}https://stackoverflow.com/questions/50797517
复制相似问题