We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
本系列文章来源于《Javascript设计模式》(张容铭版),做一个记录。
这一节如果是对原型链理解得非常清楚的话完成不在话下。如果对原型链理解不清楚的话欢迎看我的另一篇博客avascript原型理解
原型模式就是将可复用的、可共享的、耗时大的属性从基类中提出来然后放在基类的原型中。然后子类将基类原型中的属性继承下来。对于子类中那些需要重写的方法进行重写,这样就实现了继承了。
var LoopImages = function (imgArr, container) { this.imageArray = imgArr; // 轮播图片数组 this.container = container // 轮播图片容器 } LoopImages.prototype = { constructor: LoopImages.prototype.constructor,// 原文中没有这段 createImage: function () { console.log('LoopImages createImage function'); }, changeImage: function () { console.log('LoopImages changeImage function'); } } // 上下滑动切换类 var SlideLoopImage = function (imgArr, container) { // 构造函数继承图片轮播图 LoopImages.call(this, imgArr, container); } SlideLoopImage.prototype = new LoopImages(); // 重写继承的切换下一张图片方法 SlideLoopImage.prototype.changeImage = function () { console.log('SlideLoopImg changeImage function'); } // 渐隐切换类 var FadeLoopImg = function (imgArr, container, arrow) { /** * 这里需要注意的是call,apply也是实现了继承,不过这里的继承是继承LoopImages实例自身的属性和方法 */ LoopImages.call(this, imgArr, container); this.arrow = arrow; // 切换箭头私有变量 } FadeLoopImg.prototype = new LoopImages(); // 这里其实主要是想继承LoopImages 原型上的方法我觉得这种写法欠妥下面是我的写法,欢迎指正 /** * var fc = FadeLoopImg.prototype.constructor * FadeLoopImg.prototype = LoopImages.prototype * FadeLoopImg.prototype.constructor = fc */ FadeLoopImg.prototype.changeImage = function () { console.log('FadeloopImg changeImage function'); } var fadeImage = new FadeLoopImg(['01.jpg', '02.jpg'], 'slide', ['left.jpg', 'right.jpg']) // 测试用例 console.log(fadeImage.container) console.log(fadeImage.arrow) fadeImage.changeImage();
我在代码中做了一些批注,如果有不同想法,欢迎指正。LoopImages是我们基类,在LoopImages的原型中我们设置了两个方法,以FadeLoopImg为例我们给FadeLoopImg的原型赋值new LoopImages()的实例,这样FadeLoopImg的实例就能调用LoopImages原型中的方法了,在FadeLoopImg的原型中我们实现了changeImage方法,这样在FadeLoopImg的实例调用changeImage方法时就会直接在FadeLoopImg的原型中找从而实现了对changeImage的覆写。
The text was updated successfully, but these errors were encountered:
No branches or pull requests
本系列文章来源于《Javascript设计模式》(张容铭版),做一个记录。
这一节如果是对原型链理解得非常清楚的话完成不在话下。如果对原型链理解不清楚的话欢迎看我的另一篇博客avascript原型理解
概念
原型模式就是将可复用的、可共享的、耗时大的属性从基类中提出来然后放在基类的原型中。然后子类将基类原型中的属性继承下来。对于子类中那些需要重写的方法进行重写,这样就实现了继承了。
我在代码中做了一些批注,如果有不同想法,欢迎指正。LoopImages是我们基类,在LoopImages的原型中我们设置了两个方法,以FadeLoopImg为例我们给FadeLoopImg的原型赋值new LoopImages()的实例,这样FadeLoopImg的实例就能调用LoopImages原型中的方法了,在FadeLoopImg的原型中我们实现了changeImage方法,这样在FadeLoopImg的实例调用changeImage方法时就会直接在FadeLoopImg的原型中找从而实现了对changeImage的覆写。
The text was updated successfully, but these errors were encountered: