在JavaScript實(shí)例對(duì)象中改寫原型方法詳情
在JavaScript中,我們通??梢韵裣旅娴拇a這樣來簡(jiǎn)單地定義一個(gè)類:
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... */
然后使用下面的代碼來實(shí)例化,并訪問其中的原型方法:
var sampleInstance = new sample(); sampleInstance.func1(); sampleInstance.func2(); // call more sample object prototype functions
但是如果我們想改寫其中一個(gè)原型方法,并且不破壞原有的sample對(duì)象,如何來實(shí)現(xiàn)呢?一個(gè)最簡(jiǎn)單的方法就是再構(gòu)建一個(gè)類,使其繼承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的實(shí)例對(duì)象的func1方法,并在其中訪問了其原型方法func1,然后又在其中添加了一些額外代碼。通過這樣的方法,我們對(duì)sample的原型方法進(jìn)行了擴(kuò)展,并且沒有創(chuàng)建派生類,而且也沒有破壞sample的原型方法。
到此這篇關(guān)于在JavaScript實(shí)例對(duì)象中改寫原型方法詳情的文章就介紹到這了,更多相關(guān)在JavaScript實(shí)例對(duì)象中改寫原型方法內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
微信小程序 es6-promise.js封裝請(qǐng)求與處理異步進(jìn)程
這篇文章主要介紹了微信小程序 es6-promise.js封裝請(qǐng)求與處理異步進(jìn)程的相關(guān)資料,需要的朋友可以參考下2017-06-06
fs-extra實(shí)現(xiàn)yarn?create?tlist創(chuàng)建示例詳解
這篇文章主要為大家介紹了fs-extra實(shí)現(xiàn)yarn?create?tlist創(chuàng)建示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-01-01
JS前端模擬Excel條件格式實(shí)現(xiàn)數(shù)據(jù)條效果
這篇文章主要為大家介紹了JS前端模擬Excel條件格式實(shí)現(xiàn)數(shù)據(jù)條效果,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-02-02
JavaScript選擇器函數(shù)querySelector和querySelectorAll
這篇文章主要介紹了?JavaScript選擇器函數(shù)querySelector和querySelectorAll,下面文章圍繞querySelector和querySelectorAll的相關(guān)資料展開詳細(xì)內(nèi)容,需要的朋友可以參考一下2021-11-11

