testing_22
testing_22

Reputation: 2585

How to assign multiple properties in Javascript class with less code?

I've tried the basic use of "this". However, despite being natural coming from OOP I still found it verbose. Imagine that I had 1000 properties: I'd be in trouble.

class Question{
constructor(number, point, beginning, A, B, C){
    this.number = number;
    this.grade = grade;
    this.beginning = beginning;
    this.A = A;
    this.B = B;
    this.C = C;
}

}

So is there any way to assign properties to Javascript's objects with less code?

Upvotes: 1

Views: 1632

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370639

While you could use Object.assign and shorthand properties:

constructor(number, point, beginning, A, B, C){
    Object.assign(
        this,
        {
            number,
            grade,
            beginning,
            A,
            B,
            C,
        }
    );
}

Once you start to get a lot of parameters, it can be difficult for the caller to understand what's going on. Eg:

new Question(8, 5, 2, 's', 33, 9)

It may be quite unclear from the caller what all those properties refer to. You could pass a single object as a parameter instead, which both makes it clear from the caller's perspective which properties correspond to which value, and makes the constructor much more concise:

const q = new Question({
    number: 8,
    grade: 5,
    // ...
});
constructor(props) {
    Object.assign(this, props);
}

All that said, if your Question really doesn't have anything other than the constructor, I'd omit the class entirely and use a plain object literal; the class isn't providing any benefit.

const q = {
  number: 8,
  grade: 5,
  // ...
};

Upvotes: 4

Related Questions