一,什么是原型模式
原型模式(Prototype):用原型实例指向创建对象的类,使用于创建新的对象的类共享原型对象的属性以及方法。
// 图片轮播类var LoopImages = function(imgArr, container) {this.imagesArray = 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) {LoopImages.call(this. imgArr, container);// 切换箭头私有变量this.arrow = arrow;}FadeLoopImg.prototype = new LoopImages();FadeLoopImg.prototype.changeImage = function() {console.log('FadeLoopImg changeImage function');}
测试用例:
var imgArr = ['01.jpg', '02.jpg', '03.jpg'];var container = 'slide';var arrow = ['left.jpg', 'right.jpg'];var fadeImg = new FadeLoopImg(imgArr, container, arrow);console.log(fadeImg.container); // slidefadeImg.changeImage(); // FadeLoopImg changeImage function
二,原型的拓展
LoopImages.prototype.getImageLength = function() {return this.imagessArray.length;}FadeLoopImg.prototype.getContainer = function() {return this.container;}console.log(fadeImg.getImageLength()); // 4console.log(fadeImg.getContainer()); // slide
三,原型的继承
基于已经存在的模板对象克隆出新对象的模式
function prototypeExtend() {var F = function() {},args = arguments,i = 0,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(); // 游泳速度:20penguin.run(10); // 奔跑速度:10penguin.jump(); // 跳跃动作
