简体   繁体   中英

Prototypal Inheritance in JavaScript…Can I call a “super” equivalent?

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?
    };
};

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, []);
    };
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM