【问题标题】:JS - why would child class method call parent class method using Parent.prototype.method.call?JS - 为什么子类方法会使用 Parent.prototype.method.call 调用父类方法?
【发布时间】:2021-08-24 23:33:16
【问题描述】:

我想使用伪经典模式从父类调用一个方法,作为 JavaScript 中子类方法的一部分。我看过代码示例,其中父类方法由“Parent.prototype.parentMethod.call(this)”调用,如下所示:

function Parent(arg1) {
  this.arg1 = arg1;
}

Parent.prototype.parentMethod = function() {
  return `Argument 1 is: ${this.arg1}`;
};

function Child(arg1, arg2) {
  Parent.call(this, arg1);
  this.arg2 = arg2;
}

Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;

Child.prototype.childMethod = function() {
  return `${Parent.prototype.parentMethod.call(this)} and Argument 2 is: ${this.arg2}`;
};

在实现子方法时,为什么有必要(或希望)做 'Parent.prototype.parentMethod.call(this)' 而不仅仅是 'this.parentMethod'?原型链不应该让'this.parentMethod'成为可能吗?

【问题讨论】:

  • 请问你这个原始的 sn-p 是从哪里得到的?也许源周围有一些上下文可以表明为什么它被称为这种方式。但是,从您单独发布的内容来看,我会说以这种方式调用父方法既没有必要也不可取。正如您所注意到的,您可以只使用this.parentMethod(),它更短,而且 IMO 的意图更明确。
  • 你需要阅读,How this works in Javascript

标签: javascript inheritance


【解决方案1】:

原型链不应该让this.parentMethod()成为可能吗?

是的,这是可能的。

为什么有必要(或希望)做Parent.prototype.parentMethod.call(this) 而不仅仅是this.parentMethod

当您想要调用该特定方法(父级的实现)而不是可能被覆盖的this.parentMethod 时,这是可取的。

这在自己重写方法的时候是必不可少的(必须的),并且你想调用被重写的方法:

function Parent(arg1) {
  this.arg1 = arg1;
}
Parent.prototype.method = function() {
  return `Argument 1 is: ${this.arg1}`;
};

function Child(arg1, arg2) {
  Parent.call(this, arg1);
  this.arg2 = arg2;
}
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
Child.prototype.method = function() {
  return `${Parent.prototype.method.call(this)} and Argument 2 is: ${this.arg2}`;
};

调用 this.method() 会导致递归(和堆栈溢出)。

注意现代的写法是

class Parent {
  constructor(arg1) {
    this.arg1 = arg1;
  }
  method() {
    return `Argument 1 is: ${this.arg1}`;
  }
}
class Child {
  constructor(arg1, arg2) {
    super(arg1);
    this.arg2 = arg2;
  }
  method() {
    return `${super.method()} and Argument 2 is: ${this.arg2}`;
  }
}

super.method() 与旧语法完全相同。

【讨论】:

    猜你喜欢
    • 2017-10-31
    • 2016-02-14
    • 2017-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    • 2011-09-04
    • 2012-02-22
    相关资源
    最近更新 更多