JavaScript进阶:原型模式
2022-01-21 本文已影响0人
听书先生
1、前言
原型模式是指的将原型对象指向创建对象的类,使得不同的类共享原型对象的方法和属性。
js中基于原型链的继承的原理本质上就是对继承过来的类的属性和方法的共享,并不是对属性和方法的拷贝。
-
示例1:创建轮播类
在LoopImg
这个类中定义轮播的相关属性和方法,轮播图的轮播方式有很多种,比如:左右滑动,3D翻转等等。因此,后面定义这两个类使用call()
方法将属性执行父类的构造函数,然后在内部修改switchImg
切换的方法。
// 创建一个轮播图
const LoopImg = function(arrImg, container){
this.arrImg = arrImg;
this.container = container;
this.createImg = function() {}
this.switchImg = function() {}
}
// 创建一个左右滑动效果的轮播
const SlideLoopImg = function(arrImg, container, arrow) {
LoopImg.call(this, arrImg, container);
this.arrow = arrow;
this.switchImg = function() {
console.log('left and right sliding rotation chart');
}
}
// 创建一个左右3D转动效果的轮播
const RotateLoopImg = function(arrImg, container) {
LoopImg.call(this, arrImg, container);
this.switchImg = function() {
console.log('rotation of left-right sliding effect');
}
}
const loop = new RotateLoopImg( ['1.png','2.png','3.png'], 'rotate');
loop.switchImg(); // rotation of left-right sliding effect'
-
存在的问题以及优化方案:
LoopImg
作为基类是要被子类继承的,如果将大量的基类的方法写在构造函数中,就会导致每次子类继承一次基类,就会执行一遍基类内部的方法,就做了大量的重复性的操作。
为了优化性能,我们普遍将简单的一些属性赋值操作放在基类的构造函数中,复杂的逻辑处理放在原型对象链上,这样完成了方法共享的同时提高了性能。
// 解决方案的优化
const LoopImg = function(arrImg, container){
this.arrImg = arrImg;
this.container = container;
}
// LoopImg类的原型上添加方法
LoopImg.prototype = {
createImg: function() {
},
switchImg: function() {
}
}
const SlideLoopImg = function(arrImg, container, arrow) {
LoopImg.call(this, arrImg, container);
this.arrow = arrow;
}
SlideLoopImg.prototype = new LoopImg();
SlideLoopImg.prototype.switchImg = function() {
console.log('Up and down sliding rotation chart');
}
const RotateLoopImg = function(arrImg, container) {
LoopImg.call(this, arrImg, container);
}
RotateLoopImg.prototype = new LoopImg();
RotateLoopImg.prototype.switchImg = function() {
console.log('Rotation of left-right sliding effect');
}
const loop = new RotateLoopImg(
['1.png','2.png','3.png'],
'rotate'
);
loop.switchImg();