我如何在 javascript 中使用许多参数扩展 class

How can i extend a class with many pararms in javascript

class A{
 constructor(p1,p2,p3){
    this.p1=p1;
    this.p2=p2;
    this.p3=p3;
 }
}
class B extends A{
 constructor(p1,p2,p3,p4,p5){
    super(p1,p2,p3);
    this.p4=p4;
    this.p5=p5;
 }
}

我已经学会了使用这种形式,但仍然不知道如何通过可读的方式扩展Class具有许多参数的 A

class A{
 constructor(obj){
    this.p1=obj.p1;
    this.p2=obj.p2;
    this.p3=obj.p3;
 }
}

如果我的代码不是最好的方法,请告诉我怎么做,谢谢!

更多问题

@T.J。克劳德 我尝试使用 选项对象 来扩展 class A 但它不起作用,我错过了什么?

class A{
 constructor(opt){
  this.p1=opt.p1;
  this.p2=opt.p2;
  this.p3=opt.p3;
 }
}
class B extends A{
 constructor(opt){
  super(opt.p1,opt.p2,opt.p3);
  this.p4=opt.p4;
  this.p5=opt.p5;
 }
}
var instant=new B({p1:1,p2:2,p3:3,p4:4,p5:5});
console.log('p1:'+instant.p1);
console.log('p2:'+instant.p2);
console.log('p5:'+instant.p5);

输出为p1:undefind;p2:undefind;p5:5

当您认为某个函数或构造函数的参数太多并且很难保持它们的正确性时,一种常见的方法是使用 options 对象,或者可能是一两个参数和一个可选的选项对象。

例如:

constructor(options) {
    super(options.p1, options.p2, options.p3);
    // ...use options.p4 and options.p5 here...
}

你称之为传入一个对象:

new B({p1: "x", p2: "y", /*...*/});

如果愿意,您可以在参数列表中使用解构,以获取选项对象属性的各个局部变量:

constructor({p1, p2, p3, p4, p5}) {
    super(p1, p2, p3);
    // ...use p4 and p5 here...
}

您甚至可以更新 A 以便接受选项对象而不是离散参数。例如:

class A {
    constructor({p1, p2, p3}) {
        // ...use p1, p2, and p3 here...
    }
}

class B extends A {
    constructor({p1, p2, p3, p4, p5}) {
        super({p1, p2, p3});
        // ...use p4 and p5 here...
    }
}

假设您的 child class B 在末尾添加了它需要的属性,并且第一个总是用于 A,那么您可以使用spread syntax with the arguments object 每个函数接收:

class A{
 constructor(p1,p2,p3){
    this.p1=p1;
    this.p2=p2;
    this.p3=p3;
 }
}
class B extends A{
 constructor(p1,p2,p3,p4,p5){
    super(...arguments);
//        ^^^ spread the arguments to call the super constructor
    this.p4=p4;
    this.p5=p5
 }
}

const instance = new B("one", "two", "three", "four", "five");

console.log("instance.p1:", instance.p1);
console.log("instance.p2:", instance.p2);
console.log("instance.p3:", instance.p3);
console.log("instance.p4:", instance.p4);
console.log("instance.p5:", instance.p5);

这将有效调用 super(p1, p2, p3, p4, p5),但是由于 A 的构造函数只关心前三个参数,它将忽略其余参数。

您可以在构造函数中将 objthis 合并,方法如下

constructor (obj) {
  Object.assign(this, obj);
  console.log(this.p1, this.p2);
}