硬编码Javascript构造函数参数是否可以?

时间:2018-10-25 05:11:32

标签: javascript es6-class

我正在玩Java类和继承,但是我不了解构造函数的一部分。在我的父类中,我hard-coded bankAccountStatus达到以下值Bank Account is Low。然后,我创建了一个名为MemberStatus的子类,并将构造函数参数定义为与父类相同的输入。但是,如果我在调用bankAccountStatus时尝试将new MemberStatus更改为其他名称,则不会。我当然可以将其更改为参数名称,以使其正常工作,但是我试图理解其功能。是否有必要更改该值而无需在父类中将其转换为this.bankAccountStatus = bankAccountStatus;

class User {
  constructor(firstName, lastName, phone, bankAccountStatus){
    this.firstName = firstName;
    this.lastName = lastName;
    this.phone = phone;
    this.bankAccountStatus = 'Bank Account is Low';
  }
}

class MemberStatus extends User {
  constructor(firstName, lastName, phone, bankAccountStatus, vipStatus){
    super(firstName, lastName, phone, bankAccountStatus);
    this.vipStatus = vipStatus;
  }
}

let john = new MemberStatus('John', 'Doe', '555-123-4567', 'Bank Account is Wealthy', 'Gold');
console.log(john);

2 个答案:

答案 0 :(得分:2)

如果要默认将其添加到User的构造函数中,为什么要麻烦呢?扩展类的构造函数不必相同:

class User {
  constructor(firstName, lastName, phone){
    this.firstName = firstName;
    this.lastName = lastName;
    this.phone = phone;
    this.bankAccountStatus = 'Bank Account is Low';
  }
}

class MemberStatus extends User {
  constructor(firstName, lastName, phone, bankAccountStatus, vipStatus){
    super(firstName, lastName, phone);
    this.bankAccountStatus = bankAccountStatus
    this.vipStatus = vipStatus;
  }
}

let john = new MemberStatus('John', 'Doe', '555-123-4567', 'Bank Account is Wealthy', 'Gold');
console.log(john);

答案 1 :(得分:1)

您问:

  

无论如何都可以更改该值,而无需在父类中将其转换为this.bankAccountStatus = bankAccountStatus

如果您看一下构造函数:

class User {
  constructor(firstName, lastName, phone, bankAccountStatus){
    this.firstName = firstName;
    this.lastName = lastName;
    this.phone = phone;
    this.bankAccountStatus = 'Bank Account is Low';
  }
}

class MemberStatus extends User {
  constructor(firstName, lastName, phone, bankAccountStatus, vipStatus){
    super(firstName, lastName, phone, bankAccountStatus);
    this.vipStatus = vipStatus;
  }
}

您正在传递字符串作为您的第四个用户变量参数,但是您从未访问过它。如果您想为this.bankAccountStatus提供默认值,可以将其放在参数中,如下所示:

class User {
  constructor(firstName, lastName, phone, bankAccountStatus = 'Bank Account is Low'){
    this.firstName = firstName;
    this.lastName = lastName;
    this.phone = phone;
    this.bankAccountStatus = bankAccountStatus;
  }
}

祝您的项目好运!