欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

在JavaScript實例對象中改寫原型方法詳情

 更新時間:2021年10月12日 15:08:03   作者:Jaxu  
這篇文章主要介紹了在JavaScript實例對象中改寫原型方法的一下相關(guān)資料,需要的效果版可以參考一下文章詳細(xì)內(nèi)容,希望對你有所幫助

JavaScript中,我們通??梢韵裣旅娴拇a這樣來簡單地定義一個類:

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對象,如何來實現(xiàn)呢?一個最簡單的方法就是再構(gòu)建一個類,使其繼承sample,然后在繼承類的原型方法中改寫基類的方法,就像下面這樣:

var subSample = function() {
    // constructor code here
}

// inherit from sample
subSample.prototype = new sample();
subSample.prototype.fun1 = function() {
    // overwrite the sample's func1
}

但是如果沒有構(gòu)建繼承類,而想改寫原型方法,可以直接使用下面的代碼:

var sampleInstance = new sample();
sampleInstance.func1 = function() {
    sample.prototype.fun1.call(this); // call sample's func1
    // sampleInstance.func1 code here
}


我們重新定義了sample的實例對象的func1方法,并在其中訪問了其原型方法func1,然后又在其中添加了一些額外代碼。通過這樣的方法,我們對sample的原型方法進(jìn)行了擴(kuò)展,并且沒有創(chuàng)建派生類,而且也沒有破壞sample的原型方法。

到此這篇關(guān)于在JavaScript實例對象中改寫原型方法詳情的文章就介紹到這了,更多相關(guān)在JavaScript實例對象中改寫原型方法內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論