Javascript继承 - 覆盖超级功能

时间:2013-11-12 18:39:22

标签: javascript inheritance

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

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

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

3 个答案:

答案 0 :(得分: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!

答案 1 :(得分:0)

在替换之前保存副本。

function subClass(){
    var prevSuper = this.superFunction;
    this.superFunction = function(arg){
        //call super function()
        prevSuper(arg);
        //aditional code bellow
        //...
    }   
}

答案 2 :(得分:0)

您可以使用“通话”

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

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