【问题标题】:How to use an object as an argument in JavaScript subclasses?如何在 JavaScript 子类中使用对象作为参数?
【发布时间】:2021-12-29 18:49:55
【问题描述】:

例如,如果我有这样的事情:

class X{
    constructor({one, two}){
        this.one = one 
        this.two = two
    }
}

class Y extends X{
    constructor(props, three){
        super(props)
        this.three = three
    }
}

我想创建一个对象:

console.log(new Y({one: 1, two: 2, three: 3}))

有可能吗?我尝试了其他方法,例如:

console.log(new Y({one: 1, two: 2}, 3))
console.log(new Y({one: 1, two: 2}, {three: 3}))

但他们不舒服。

【问题讨论】:

  • 使用this.three = props.three。不要添加第二个参数。

标签: javascript class inheritance subclass


【解决方案1】:

你可以这样做...
simply use Destructuring assignment

class X {
  constructor({one, two}) {
    this.one = one 
    this.two = two
  }
  displaying() {
    console.log(this)
  }
}

class Y extends X {
  constructor({three, ...OneTwo}) {
    super(OneTwo)
    this.three = three
  }
}

let zz = new Y({one: 1, two: 2, three: 3})

zz.displaying()

【讨论】:

  • 好答案!在你的第一个例子中,稍微修正了一个错误。您还需要在类 Y 的构造函数中添加three 作为第二个参数:constructor(props, three)。此外,除了在第一个示例中使用道具之外,您还可以像这样解构变量 onetwoconstructor ({one, two}, three) 然后在调用 super 时不需要点符号
  • 哎呀,看来我没时间完成我的第一条评论的编辑了。想要补充一点,如果你想让参数成为一个对象,就像你调用它的方式一样,那么你也可以解构three,而不是作为一个单独的参数传递并将其用作自己的变量。
  • @hoekma 你是对的,我的第一个例子是错误的并且不必要地复杂
猜你喜欢
  • 1970-01-01
  • 2021-12-15
  • 1970-01-01
  • 1970-01-01
  • 2016-04-09
  • 1970-01-01
  • 1970-01-01
  • 2023-01-07
  • 1970-01-01
相关资源
最近更新 更多