2011-01-24 96 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(); 

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