Javascript继承和方法覆盖

时间:2011-01-24 00:22:47

标签: javascript inheritance prototype

假设我有这样的课程:

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

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

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

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

5 个答案:

答案 0 :(得分:40)

您可以像这样模拟它:

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

或者您可以创建自己的超级属性:

SpecialWidget.prototype.parent = Widget.prototype;

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

答案 1 :(得分:2)

首先,你设置你的'子类'是这样的

function SubClass(name) {
    Super.call(this);

    // stuff here
}

SubClass.prototype = new SuperClass(null);
SubClass.prototype.constructor = SubClass;

然后你可以做

SuperClass.prototype.theMethod.apply(this);

从子类实现中专门调用super的实现。

答案 2 :(得分:1)

我不知道这是否是最佳解决方案,但您可以这样做:

function Widget() {
    this.id = new Date().getTime();
}
Widget.prototype.load = function(args) {
   alert( 'parent load' );
};

SpecialWidget = function(){};

   // Make the prototype of SpecialWidget an instance of Widget
var proto = SpecialWidget.prototype = new Widget;

   // Give the prototype a function that references the "load" from Widget
proto.parent_load = proto.load;

   // Give SpecialWidget its own "load" that first calls the parent_load
proto.load = function( args ) {
    this.parent_load( args );
    alert( 'special load' );
};

var inst = new SpecialWidget;

inst.load();

这使得SpecialWidget的原型成为Widget的一个实例,以便它继承Widget所拥有的所有内容。

然后它引用load() Widget parent_load(),并调用load(),调用时parent_load()

答案 3 :(得分:0)

如果你按照这样做覆盖,可以将load方法的旧值存储在闭包中:

function Widget() {
    this.id = new Date().getTime();
    // other fields
}

Widget.prototype = {
    load: function(args) {
        // do something
        alert("Widget Prototype Load");
    }
};

function SpecialWidget(){
};

SpecialWidget.prototype = new Widget();

(function(){
    var oldLoad = SpecialWidget.prototype.load;
    SpecialWidget.prototype.load = function(){
        oldLoad();
        alert("new Load");
    };
}());


var x = new SpecialWidget();
x.load();

它有效,但我不确定它是否是最好的方法。

答案 4 :(得分:0)

使用Simple Javascript Class

Class.extend('Widget', {
  load: function () {
    alert('foo');
  }
});

Widget.extend('SpecialWidget', {
  load: function () {
    this.super();
    alert('bar');
  }
});

new Widget().load(); // Alert: 'foo'
new SpecialWidget().load(); // Alert: 'foo' and 'bar'

查看Simple Javascript Class ProjectSimple JavaScript InheritanceInheritance Patterns in JavaScript

相关问题