关键是:
superClass.prototype.superFunction.call(this, arg);
但首先,您永远不会将 附加superFunction
到原型,superClass
而只是将其声明为简单的公共属性:
function superClass(){
this.superFunction = function(arg){
// ...
}
}
console.log(superClass.prototype);
> superClass {}
所以要实现你想要的行为:
function superClass(){
}
superClass.prototype.superFunction = function (arg) {
console.log(arg+' from parent!');
}
function subClass(){
}
subClass.prototype = new superClass();
// At this point a 'superFunction' already exists
// in the prototype of 'subClass' ("Inherited" from superClass)
// Here, we're overriding it:
subClass.prototype.superFunction = function(arg){
superClass.prototype.superFunction.call(this, arg);
console.log(arg+' from child!');
}
var childCl = new subClass();
childCl.superFunction('Hello ');
> Hello from parent!
> Hello from child!