【问题标题】:Why does a parent class method doesn't pass the argument when calling another parent method while the child class has methods with identical names?为什么父类方法在调用另一个父方法时不传递参数,而子类有同名的方法?
【发布时间】:2021-10-19 11:43:22
【问题描述】:

我遇到了以下情况。我有一个父类和一个子类,其中有 2-2 个名称相同的方法 ab。父方法 a 需要一个附加参数,该参数由另一个父方法 b 传递给它。但是,当尝试访问调用的 a 方法中的参数时,它是 undefined

如果我在父级或子级中更改方法 a 的名称,我会得到预期的结果并传递参数。

我也明白父母和孩子的 a 方法都被调用了。但是,我不明白为什么无论如何都没有通过论点。我还想知道除了重命名方法之外,是否还有其他方法可以避免这种行为?

class Test {
  constructor() {}

  a(param1, param2) {
    console.log('a in parent invoked')
    console.log(param2)
  }

  b(param1) {

    const param2 = 2
    this.a(param1, param2)
  }
}

class TestChild extends Test {
  constructor() {
    super()
  }

  a(param1) {
    console.log('a in child invoked')
    return super.a(param1)

  }

  b(param1) {
    return super.b(param1)
  }
}

const test = new TestChild()
test.b(1)

【问题讨论】:

  • TestChild 方法a 调用Test 方法a 一个参数...super.a(param1) - 你认为param2 会从哪里来?

标签: javascript class inheritance arguments


【解决方案1】:

Test.prototype.b 使用两个参数调用this.a(…),当在子实例上调用时解析为被覆盖 TestChild.prototype.aTestChild.prototype.a 方法调用super.a(param1),忽略传递第二个参数。这违反了子类约定,因为它没有实现与父方法相同的接口,并且调用父方法时参数不足。

如果你改成

class TestChild extends Test {
  a(param1, ...args) {
    console.log('a in child invoked')
    return super.a(param1, ...args)
  }
}

它将按预期工作。 (或者更好的是,只需明确地拼出param2 - 我不确定你为什么希望子类一开始就少一个参数)。也许

class TestChild extends Test {
  a(param1, param2 = 'default') {
    console.log('a in child invoked')
    return super.a(param1, param2)
  }
}

那么test.b(1)test.a(1) 都可以使用。

【讨论】:

  • 谢谢!所以我可以在 Test.b 中显式调用 Test.prototype.a ,这也可以解决我的问题。但据我了解,子类方法应该实现与父类相同的接口。明白了!
  • 确实,Test.prototype.a.call(this, param1, param2) 也可以,但这不是您通常想要的可以被覆盖的方法。
猜你喜欢
  • 1970-01-01
  • 2014-01-22
  • 1970-01-01
  • 2016-02-14
  • 1970-01-01
  • 2017-11-09
  • 2021-08-24
  • 2021-04-08
  • 1970-01-01
相关资源
最近更新 更多