为什么 parent class 方法在调用另一个 parent 方法时不传递参数,而 child class 具有相同名称的方法?

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?

我遇到了以下情况。我有一个 parent class 和一个 child class 以及 2-2 个相同命名的方法 ab 。 parent 中的方法 a 需要一个额外的参数,该参数由另一个 parent 方法 b 传递给它。但是,当尝试访问调用的 a 方法中的参数时,它是 undefined.

如果我在 parent 或 child 中更改方法 a 的名称,我会得到我期望的结果并且参数被传递。

我也了解到 parents' 和 child 的 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)

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) 都可以。