首页 > 解决方案 > 具有默认值的 JavaScript 类继承并处理许多属性

问题描述

正如这篇优秀的文章中所述,可以继承/子类/扩展这样的 JS 类,例如:

class Column {
  constructor(name, align = 'right') {
    this.name = name;
    this.align = align
  }
}

numberFormat = "I'm defined somewhere else"
class FloatColumn extends Column {
  constructor(name, align, format = numberFormat) {
    super(name, align);
    //super(name); Here the instance get's constructed with default value for align as defined in Column
    this.format = format
  }
}
console.log(new Column('col1'))
console.log(new FloatColumn('col2', 'left'))

让我们假设后续代码正在将Column实例解析(和相关)到创建表列的其他东西(我的用例是简化webix 数据表列定义并使它们保持一致)。由于这段代码已经定义了大量的属性(带有默认值),我不需要在Column. 要为某些属性设置默认值,同时允许解析任何其他属性,kwargs我可以执行以下操作:

class Column {
  constructor({prop1=1, prop2 = 2, prop3 = 3, prop4 = 4, prop5=5, prop6=6, ...kwargs}) {
    Object.assign(this, {prop1, prop2, prop3, prop4, prop5, prop6, ...kwargs})
  }
}

numberFormat = "I'm defined somewhere else"
class FloatColumn extends Column {
  constructor({format = numberFormat, ...kwargs}) {
    super({format, ...kwargs});
    this.format = format
  }
}
console.log(new Column({prop1:100, align:'right', height:25, width:100}))
console.log(new FloatColumn({format:'CustomFormat'}))

有没有比上述方法更好的方法?理想情况下,我想以下列方式定义默认属性值,但这可能只是其他语言的遗留问题,在 JS 中不可行。

class Column {
  prop1 = 1 
  prop2 = 2
  prop3 = 3
  prop4 = 4
  prop5 = 5
  prop6 = 6
  constructor(kwargs) {
    Object.assign(this, kwargs)
  }
}

numberFormat = "I'm defined somewhere else"
class FloatColumn extends Column {
  format = numberFormat
  prop5 = 999
  constructor({ format, ...kwargs}) {
    super({format, ...kwargs});
    this.format = format
  }
}
console.log(new Column({prop1:100, align:'right', height:25, width:100}))
console.log(new FloatColumn({format:'CustomFormat', prop5:111}))

这种方法不起作用,prop1 到 prop6 未定义。
更新:调整了这个片段,感谢@VLAZ 评论由于字段初始化字段的顺序prop5现在总是设置为 999,并且在创建FloatColumn. 如何做到这一点?

标签: javascriptclassinheritanceconstructor

解决方案


推荐阅读