[英]Change default value of an attribute in constructor class in Javascript
I have a class Action below.我在下面有一个 class 动作。 Default values for _actionOver and _peopleAffected are defined.
定义了_actionOver和_peopleAffected的默认值。
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现在我定义这个 class 的新 object 并更改actionOver和_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.如果我更改了 object 中的值,它不应该给出true和10作为 output。 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.您只是忽略了构造函数 arguments 并始终分配相同的初始值。
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.您没有分配默认值,您只是分配了一个值并忽略了作为 arguments 传递的值。
Once you defined your default:一旦你定义了你的默认值:
this._actionOver=false;
You must check if other values have been passed via arguments and overwrite the defaults:您必须检查其他值是否已通过 arguments 传递并覆盖默认值:
this._actionOver=false;
if (actionOver) this._actionOver = actionOver;
You can do a one liner:你可以做一个衬里:
this._actionOver = actionOver || false;
Or just use function parameter defaults:或者只使用 function 参数默认值:
constructor(staffName, description, actionOver = false, peopleAffected = 0){
// ....
this._actionOver=actionOver;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.