Igor Shvets
Igor Shvets

Reputation: 547

How to change one property of a constructor without affecting others?

How to change one property of the constructor in the method "refactorGroupInfo", so that others would not be "undefined". Or how to make this method universal so that you can change one property of the constructor, or all

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

Upvotes: 0

Views: 55

Answers (2)

Orelsanpls
Orelsanpls

Reputation: 23505

I would prefer to use an object, so every key you define inside is modified.

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

Upvotes: 2

JED
JED

Reputation: 1694

in your refactorGroupInfo function, you could add a check to see if the parameters of the function haven't been defined.

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

Upvotes: 1

Related Questions