JavaScript進(jìn)階:原型模式

1、前言

原型模式是指的將原型對象指向創(chuàng)建對象的類,使得不同的類共享原型對象的方法和屬性。
js中基于原型鏈的繼承的原理本質(zhì)上就是對繼承過來的類的屬性和方法的共享,并不是對屬性和方法的拷貝。

  • 示例1:創(chuàng)建輪播類
    LoopImg這個類中定義輪播的相關(guān)屬性和方法,輪播圖的輪播方式有很多種,比如:左右滑動,3D翻轉(zhuǎn)等等。因此,后面定義這兩個類使用call()方法將屬性執(zhí)行父類的構(gòu)造函數(shù),然后在內(nèi)部修改switchImg切換的方法。
// 創(chuàng)建一個輪播圖
const LoopImg = function(arrImg, container){
    this.arrImg = arrImg;
    this.container = container;
    this.createImg = function() {}
    this.switchImg = function() {}
}

// 創(chuàng)建一個左右滑動效果的輪播
const SlideLoopImg = function(arrImg, container, arrow) {
    LoopImg.call(this, arrImg, container);
    this.arrow = arrow;
    this.switchImg = function() {
        console.log('left and right sliding rotation chart');
    }
}

// 創(chuàng)建一個左右3D轉(zhuǎn)動效果的輪播
const RotateLoopImg = function(arrImg, container) {
    LoopImg.call(this, arrImg, container);
    this.switchImg = function() {
        console.log('rotation of left-right sliding effect');
    }
}

const loop = new RotateLoopImg( ['1.png','2.png','3.png'], 'rotate');

loop.switchImg();  // rotation of left-right sliding effect'
  • 存在的問題以及優(yōu)化方案:
    LoopImg作為基類是要被子類繼承的,如果將大量的基類的方法寫在構(gòu)造函數(shù)中,就會導(dǎo)致每次子類繼承一次基類,就會執(zhí)行一遍基類內(nèi)部的方法,就做了大量的重復(fù)性的操作。
    為了優(yōu)化性能,我們普遍將簡單的一些屬性賦值操作放在基類的構(gòu)造函數(shù)中,復(fù)雜的邏輯處理放在原型對象鏈上,這樣完成了方法共享的同時(shí)提高了性能。
// 解決方案的優(yōu)化
const LoopImg = function(arrImg, container){
    this.arrImg = arrImg;
    this.container = container;
}

// LoopImg類的原型上添加方法
LoopImg.prototype = {
    createImg: function() {
        
    },
    switchImg: function() {
        
    }
}

const SlideLoopImg = function(arrImg, container, arrow) {
    LoopImg.call(this, arrImg, container);
    this.arrow = arrow;
}
SlideLoopImg.prototype = new LoopImg();

SlideLoopImg.prototype.switchImg = function() {
    console.log('Up and down sliding rotation chart');
}

const RotateLoopImg = function(arrImg, container) {
    LoopImg.call(this, arrImg, container);
}
RotateLoopImg.prototype = new LoopImg();

RotateLoopImg.prototype.switchImg = function() {
    console.log('Rotation of left-right sliding effect');
}

const loop = new RotateLoopImg(
    ['1.png','2.png','3.png'],
    'rotate'
);

loop.switchImg();
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容