JavaScript中的Prototypal继承......我可以称之为“超级”吗?当量? [英] Prototypal Inheritance in JavaScript...Can I call a "super" equivalent?

查看:67
本文介绍了JavaScript中的Prototypal继承......我可以称之为“超级”吗?当量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用原型继承在javascript中构建面向对象的库。与Java和.NET类似,我的所有对象/原型都将继承Object对象/原型。我想知道是否可以从派生函数中调用超级对象/原型函数?

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?

考虑下面的代码例子:

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

function CustomObject() {
    this.DoAction = function() {
        super.DoAction();    //How do I do this in JavaScript?
    };
};


推荐答案

JavaScript没有直接相当于 super

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(); 
    };
};

如果您能够使用ES5功能,则可以使用 Object.getPrototypeOf 从原型中获取方法,然后应用以当前对象执行它 this

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

这篇关于JavaScript中的Prototypal继承......我可以称之为“超级”吗?当量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆