Calling overridden methods in JavaScript

孤街浪徒 提交于 2019-12-06 12:52:08

You can use a property to store the class' parent and call methods directly on the parent class:

function BaseClass() {
}
BaseClass.prototype.foo = function() {
    console.log('called BaseClass.foo');
};

SubClass = function() {
};
SubClass.prototype = new BaseClass;
SubClass.prototype.__super__ = BaseClass;
SubClass.prototype.foo = function() {
    console.log('called SubClass.foo');

    // calling super.foo();
    this.__super__.prototype.foo.call(this);
};

You can add a little abstraction:

// The `clazz` parameter allows super-classes to use super() too.
// It should be the calling class
BaseClass.prototype.super = function(clazz, functionName) {
    // take all the arguments after functionName
    var args = Array.prototype.slice.call(arguments, 2);
    // call the function on super's prototype
    clazz.prototype.__super__.prototype[functionName].apply(this, args);
};

You can use it like this:

SubClass.prototype.foo = function() {
    console.log('called SubClass.foo');

    // calling super.foo();
    // Pass the calling class as first parameter
    this.super(SubClass, 'foo');
};    

Try it here: http://jsfiddle.net/ZWZP6/2/

In CoffeeScript

In coffee script you can use the super()[docs] construct:

class BaseClass
    foo: -> console.log('called BaseClass.foo')

class SubClass extends BaseClass
    foo: ->
        console.log('called SubClass.foo')
        super()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!