在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的原型方法。