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?
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;
// ^^^^^^^^^^^^^^
}
You're not assigning a default value, you're just assigning a value and ignoring the values passed as arguments.
Once you defined your default:
this._actionOver=false;
You must check if other values have been passed via arguments and overwrite the defaults:
this._actionOver=false;
if (actionOver) this._actionOver = actionOver;
You can do a one liner:
this._actionOver = actionOver || false;
Or just use function parameter defaults:
constructor(staffName, description, actionOver = false, peopleAffected = 0){
// ....
this._actionOver=actionOver;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.