7.第二篇:第7章 原型模式

本文摘自 《JavaScript 设计模式》张容铭 著 版权归原作者所有

// 图片轮播类
var LoopImages = function(imgArr,container){
  this.imageArray = imgArr; // 轮播图片数组
  this.container = container; // 轮播图片容器
}

LoopImages.prototype = {
  // 创建轮播图片
  createImage : function(){
    console.log('LoopImages createImage function');
  },
  // 切换下一张图片
  changeImage : function(){
    console.log('LoopImages changeImage function')
  }
}

// 上下滑动切换类
var SlideLoopImg = function(imgArr,container){
  // 构造函数继承图片轮播类
  LoopImages.call(this,imgArr,container);
}
SlideLoopImg.prototype = new LoopImages();
// 重写继承的切换下一张图片方法
SlideLoopImg.prototype.changeImage = function(){
  console.log('SlideLoopImg changeImage function')
}

// 渐隐切换类
var FadeLoopImg = function(imgArr,container,arrow){
  LoopImage.call(this,imgArr,container);
  // 切换箭头私有变量
  this.arrow = arrow;
}
FadeLoopImg.prototype = new LoopImages();
FadeLoopImg.prototype.changeImage = function(){
  console.log('FadeLoopImg changeImage function')
}
// 测试用例
console.log(fadeImg.container); // slide
fadeImg.changeImage(); // FadeLoopImg changeImage function

原型的拓展

LoopImages.prototype.getImageLength = function(){
  return this.imageArray.length;
}
FadeLoopImages.prototype.getContainer = function(){
  return this.container;
}

console.log(fadeImg.getImageLength()) // 4

原型继承

/**
* 基于已经存在的模板对象克隆出新对象的牧师
* arguments[0],arguments[1],arguments[2]:参数1,参数2,参数3 表示模板对象
* 注意:这里对模板引用类型的属性实质上进行了浅拷贝(引用类型属性共享),根据需求可以自行深拷贝
**/
function prototypeExtend(){
  var F = function(){}, // 缓存类,为实例化返回对象临时创建
    args = arguments,
    len = args.length;
  for(; i < len; i++){
    // 遍历每个模板对象中的属性
    for(var j in args[i]){
      // 将这些属性复制到缓存类原型中
      F.prototype[j] = args[i][j];
    }
  }
  // 返回缓存类的一个实例
  return new F();
}

var penguin = prototypeExtend({
  speed:20,
  swim:function(){
    console.log('游泳速度'+this.speed);
  }
},{
  run:function(speed){
    console.log('奔跑速度'+speed);
  }
},{
  jump:function(){
    console.log('跳跃动作')
  }
})
penguin.swim(); // 游泳速度20
penguin.run(10); // 奔跑速度10
penguin.jump(); // 跳跃动作
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 174,931评论 25 709
  • 用两张图告诉你,为什么你的 App 会卡顿? - Android - 掘金 Cover 有什么料? 从这篇文章中你...
    hw1212阅读 14,465评论 2 59
  • 第十五次yy直播间/频道· 焦点父母课堂读书会 10月18日是洛阳焦点读书会第十五次课。我主持了这次课;效果还是非...
    文H阅读 3,468评论 10 4
  • 《选择》 也许没得选择 一切都是最好的安排 也许太多选择 如果一切可以重来 当生命给了你呼吸的权利时 除了生死其他...
    王子真心阅读 1,001评论 0 0
  • 假如一生只能读一本书我推荐《自私的基因》 《人与动物的区别-为什么是人成为万物之灵》 人与动物的区别不是使用工具,...
    笃行9阅读 1,943评论 0 0