在JavaScript實例對象中改寫原型方法詳情
在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)文章
Web?Animations?API實現(xiàn)一個精確計時的時鐘示例
這篇文章主要為大家介紹了Web?Animations?API實現(xiàn)一個精確計時的時鐘示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-07-07詳解JavaScript中數(shù)組的相關(guān)知識
這篇文章主要介紹了JavaScript中中數(shù)組的相關(guān)知識,是JS入門學(xué)習(xí)中的基礎(chǔ)知識,需要的朋友可以參考下2015-07-07微信小程序上滑加載下拉刷新(onscrollLower)分批加載數(shù)據(jù)(二)
這篇文章主要介紹了微信小程序上滑加載下拉刷新(onscrollLower)分批加載數(shù)據(jù)的相關(guān)資料,需要的朋友可以參考下2017-05-05Dom-api MutationObserver使用方法詳解
這篇文章主要為大家介紹了Dom-api MutationObserver使用方法詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-11-11