javascript设计模式笔记

JavaScript进阶:原型模式

2022-01-21  本文已影响0人  听书先生
1、前言

原型模式是指的将原型对象指向创建对象的类,使得不同的类共享原型对象的方法和属性。
js中基于原型链的继承的原理本质上就是对继承过来的类的属性和方法的共享,并不是对属性和方法的拷贝。

// 创建一个轮播图
const LoopImg = function(arrImg, container){
    this.arrImg = arrImg;
    this.container = container;
    this.createImg = function() {}
    this.switchImg = function() {}
}

// 创建一个左右滑动效果的轮播
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');
    }
}

// 创建一个左右3D转动效果的轮播
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'
// 解决方案的优化
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();
上一篇 下一篇

猜你喜欢

热点阅读