繁体   English   中英

更改 Javascript 中的构造函数 class 中属性的默认值

[英]Change default value of an attribute in constructor class in Javascript

我在下面有一个 class 动作。 定义了_actionOver_peopleAffected的默认值。

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

现在我定义这个 class 的新 object 并更改actionOver_peopleAffected的值

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

当我在控制台中打印这个

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

如果我更改了 object 中的值,它不应该给出true10作为 output。 如果不是,如何更改构造函数属性的默认值?

您只是忽略了构造函数 arguments 并始终分配相同的初始值。
我猜您实际上想使用默认参数值

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

您没有分配默认值,您只是分配了一个值并忽略了作为 arguments 传递的值。

一旦你定义了你的默认值:

    this._actionOver=false;

您必须检查其他值是否已通过 arguments 传递并覆盖默认值:

    this._actionOver=false;
    if (actionOver) this._actionOver = actionOver;

你可以做一个衬里:

   this._actionOver = actionOver || false;

或者只使用 function 参数默认值:

    constructor(staffName, description, actionOver = false, peopleAffected = 0){
        // ....
        this._actionOver=actionOver;
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM