2

I am building an object oriented library in javascript using prototypal inheritance. Similarly to Java and .NET, all of my objects/prototypes will inherit the "Object" object/prototype. I want to know if it is possible to call super object/prototype functions from derived ones?

Consider the following code exmaple:

function Object() {
    this.DoAction = function() {
    };
};

function CustomObject() {
    this.DoAction = function() {
        super.DoAction();    //How do I do this in JavaScript?
    };
};
Matthew Layton
  • 39,871
  • 52
  • 185
  • 313

1 Answers1

7

JavaScript does not have the direct equivalent of super.

A workaround could be to save the method on the prototype before overriding it, like:

function CustomObject() {
    this._super_DoAction = this.DoAction;
    this.DoAction = function() {
        this._super_DoAction(); 
    };
};

If you are able to use ES5 features, you can use Object.getPrototypeOf to get the method from the prototype, and then apply to execute it with the current object as this:

function CustomObject(){
    this.DoAction=function() {
        Object.getPrototypeOf(this).DoAction.apply(this, []);
    };
}
JacquesB
  • 41,662
  • 13
  • 71
  • 86