js 设计模式学习(3)
生活随笔
收集整理的這篇文章主要介紹了
js 设计模式学习(3)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
原型模式
將可復用的、可共享的、耗時大的從基類中提取出來,然后放在其原型中,然后子類通過組合繼承或者寄生組合式繼承將方法和屬性繼承下來。
?
1 //圖片輪播類 2 var LoopImages = function (imgArr, container) { 3 this.imgArray = imgArr; 4 this.container = container; 5 } 6 LoopImages.prototype = { 7 createImage: function () { 8 console.log('creat img function'); 9 }, 10 changeImage: function () { 11 console.log('change img function'); 12 } 13 } 14 15 var SlideLoopImg = function (imgArr, container) { 16 //構造函數繼承圖片輪播類 17 LoopImages.call(this, imgArr, container); 18 } 19 20 SlideLoopImg.prototype = new LoopImages(); 21 //重寫繼承切換下一張圖片的方法 22 SlideLoopImg.prototype.changeImage = function () { 23 console.log('SlideLoopImg Change Images'); 24 }原型繼承
通過prototypeExtend創建的是一個對象,我們無需再去NEW新的實例對象。
1 function prototypeExtend() { 2 var F = function () { }, 3 args = arguments, 4 i=0, 5 len = args.length; 6 7 for (; i < len; i++) { 8 for (var j in args[i]) { 9 F.prototype[j] = args[i][j]; 10 } 11 } 12 13 return new F(); 14 } 15 16 var penguin = prototypeExtend({ 17 speed: 20, 18 swim: function () { 19 console.log('游泳:' + this.speed); 20 }, 21 run: function (speed) { 22 console.log('奔跑:' + speed); 23 }, 24 jump: function () { 25 console.log('跳躍'); 26 } 27 })?
轉載于:https://www.cnblogs.com/CoffeeEddy/p/6891505.html
總結
以上是生活随笔為你收集整理的js 设计模式学习(3)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 基于线性表邻接矩阵结构的图的深度/广度优
- 下一篇: Spring MVC Servlet