Javascript继承和方法覆盖 [英] Javascript inheritance and method overriding

查看:168
本文介绍了Javascript继承和方法覆盖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这样一个类:

function Widget() {
    this.id = new Date().getTime();
    // other fields
}
Widget.prototype = {
    load: function(args) {
        // do something
    }
}

从这个类我创建了一些继承相同原型但有一些添加方法的其他类。我想要做的是能够在子类中定义一个load()方法,该方法首先调用父方法,然后执行一些代码。类似于:

From this class I created some other classes which inherit the same prototype but have some added methods. What I want to do is being able to define a load() method in the sub-classes which first calls the parent method and then execute some code. Something like:

SpecialWidget.prototype = {
    load: function(args) {
        super.load(args);
        // specific code here
    }
}

我知道Javascript中没有超级关键字,但必须有办法做到这一点。

I know there's no super keyword in Javascript but there must be a way to do this.

推荐答案

你可以像这样模拟:

SpecialWidget.prototype = {
    load: function(args) {
        Widget.prototype.load.call(this, args);
        // specific code here
    }
}

或者你可以像这样创建自己的超级属性:

Or you can create your own super property like this:

SpecialWidget.prototype.parent = Widget.prototype;

SpecialWidget.prototype = {
    load: function(args) {
        this.parent.load.call(this,args);
        // specific code here
    }
}

这篇关于Javascript继承和方法覆盖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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