欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

js 设计模式学习(3)

发布时间:2025/3/20 35 豆豆
生活随笔 收集整理的这篇文章主要介绍了 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)的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。