Search code examples
javascriptclassdefault-constructor

Change default value of an attribute in constructor class in Javascript


I have a class Action below. Default values for _actionOver and _peopleAffected are defined.

class Action {
    constructor(staffName, description, actionOver, peopleAffected){
        this._staffName=staffName;
        this._description=description;
        this._actionOver=false;
        this._peopleAffected=0;
    }

Now I define a new object of this class and change values for actionOver and _peopleAffected

let a= new Action ('Raul', 'Goal 1: Qaulity Education', true,10);

When I print this in console

console.log(a._actionOver);   *// gives false
console.log(a._peopleAffected);  *// gives 0*

Should not it give true and 10 as output, if i have changed values in object. If not how do I change default value of an constructor attribute?


Solution

  • You're just ignoring the constructor arguments and always assign the same initial value.
    I guess you actually wanted to use default parameter values?

    class Action {
        constructor(staffName, description, actionOver = false, peopleAffected = 0){
    //                                                ^^^^^^^^                ^^^^
            this._staffName = staffName;
            this._description = description;
            this._actionOver = actionOver;
    //                         ^^^^^^^^^^
            this._peopleAffected = peopleAffected;
    //                             ^^^^^^^^^^^^^^
        }