如何在不影响其他属性的情况下更改构造函数的一个属性?

时间:2018-06-11 12:15:47

标签: javascript

如何在方法“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);

2 个答案:

答案 0 :(得分:2)

我更喜欢使用一个对象,因此你在里面定义的每个键都会被修改。



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);




答案 1 :(得分:1)

在你的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;
}