2011-01-24 43 views
29

假设我有一类这样的:Javascript继承和方法重载

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中没有超级关键字,但必须有一种方法可以做到这一点。

回答

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

我想这是最简单的解决方案!谢谢 – 2011-01-24 00:57:00

+0

这给了我一个无限循环在我的代码,我不知道为什么.. – CarbonDry 2015-11-30 15:51:34

+0

只是添加到我以前的评论,我有一个对象已经从一个类继承,我想专精一个方法基本上。 – CarbonDry 2015-11-30 15:58:07

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所拥有的全部。

然后,它给Widgetload()称为parent_load()参考,并创建了自己的load()调用时调用parent_load()

+0

如果你不适合老客户,你可以使用Object.create(Thing.prototype)`而不是`new Thing`。 – LeeGee 2014-07-03 16:00:03

2

所以首先,你设置你的“子”,像这样

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

    // stuff here 
} 

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

,然后你可以做

SuperClass.prototype.theMethod.apply(this); 

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

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

它的工作原理,但我不知道这是否是最好的方法。