在JavaScript中,我們通常可以像下面的代碼這樣來簡單地定義一個類:
var sample = function() {
// constructor code here
}
sample.prototype.func1 = function() {
// func1 code here
}
sample.prototype.func2 = function() {
// func2 code here
}
/* more sample prototype functions here... */
然後使用下面的代碼來執行個體化,并通路其中的原型方法:
var sampleInstance = new sample();
sampleInstance.func1();
sampleInstance.func2();
// call more sample object prototype functions
但是如果我們想改寫其中一個原型方法,并且不破壞原有的sample對象,如何來實作呢?一個最簡單的方法就是再建構一個類,使其繼承sample,然後在繼承類的原型方法中改寫基類的方法,就像下面這樣:
var subSample = function() {
// constructor code here
}
// inherit from sample
subSample.prototype = new sample();
subSample.prototype.fun1 = function() {
// overwrite the sample's func1
}
但是如果沒有建構繼承類,而想改寫原型方法,可以直接使用下面的代碼:
var sampleInstance = new sample();
sampleInstance.func1 = function() {
sample.prototype.fun1.call(this); // call sample's func1
// sampleInstance.func1 code here
}
我們重新定義了sample的執行個體對象的func1方法,并在其中通路了其原型方法func1,然後又在其中添加了一些額外代碼。通過這樣的方法,我們對sample的原型方法進行了擴充,并且沒有建立派生類,而且也沒有破壞sample的原型方法。