0

我想覆盖超类中的一个函数来调用超函数+附加代码。我如何做到这一点?

function superClass(){
    this.superFunction = function(arg){
        //code
    }
}
function subClass(){
    this.superFunction = function(arg){
        //call super function()

        //aditional code bellow
        //...
    }   
}
subClass.prototype = new superClass();
4

3 回答 3

1

关键是:

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!
于 2013-11-12T19:16:11.353 回答
0

在替换之前保存一份副本。

function subClass(){
    var prevSuper = this.superFunction;
    this.superFunction = function(arg){
        //call super function()
        prevSuper(arg);
        //aditional code bellow
        //...
    }   
}
于 2013-11-12T18:43:38.640 回答
0

你可以使用“呼叫”

 this.superFunction = function(arg){
    return superClass.prototype.superFunction.call(this, arg);
};

使用“call”,您可以传入您所在上下文的“this”以及您想要传递的参数。通过这样做,您可以使用 superClass 方法覆盖 Class 的方法。

于 2013-11-12T19:19:22.833 回答