【发布时间】: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 的意图更明确。