javascript设计模式 – 原型模式原理与应用实例分析
作者:李小强 时间:2024-04-22 13:26:50
本文实例讲述了javascript设计模式 – 原型模式原理与应用。分享给大家供大家参考,具体如下:
介绍:在日常的开发过程中,我们经常会利用到前端模板引擎来做页面渲染,因为存在很多页面结构相同,内容不同的场景。这种场景在js层面也会遇到,
很多组件存在相同或者类似,重复的创建会导致系统的消耗,这就要用到原型模式了。将相似内容提取出来作为原型类,创建具体类时需要对原型类进行复制然后扩展。
需要注意的是,复制出来的对象在进行修改时不会影响到原型类,二者相互独立。
定义:使用原型实例指定创建对象的种类,并且通过克隆这些原型创建新的对象。原型模式是一种对象创建型模式。
场景:我们还是基于Dialog类来实现原型模式,我将所有弹窗共有的属性方法抽取出来,每次创建时通过复制其基础属性,在此基础上进行完善,然后返回新的对象。
示例:
var Dialog = function(){
this.init = function(arg){
this.element = arg.element;
this.name = arg.name;
}
this.show = function(){
console.log(this.name + ' is show -> ' + this.element);
}
};
var createDialog = function(arg){
var _dialog = function(){};
_dialog.prototype = new Dialog();
var resDia = new _dialog();
resDia.init(arg);
return resDia;
}
var notice = createDialog({name:'notice',element:'<div>notice</div>'});
var toast = createDialog({name:'toast',element:'<div>toast</div>'});
var warnin = createDialog({name:'warnin',element:'<div>warnin</div>'});
notice.show(); //notice is show -> <div>notice</div>
toast.show(); //toast is show -> <div>toast</div>
warnin.show(); //warnin is show -> <div>warnin</div>
原型模式总结:
优点:
* 当创建新的对象实例较为复杂时,使用原型模式可以简化对象的创建过程,通过复制一个已有实例可以提高新实例的创建效率。
* 扩展性较好
缺点:
* 对已有类进行改造时需要修改源代码,违背了开关原则。
希望本文所述对大家JavaScript程序设计有所帮助。
来源:http://www.isjs.cn/?p=959
标签:javascript,设计模式,原型模式
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
使用python从三个角度解决josephus问题的方法
2022-02-22 02:19:55
Python绘制柱状图可视化神器pyecharts
2023-06-07 12:38:41
![](https://img.aspxhome.com/file/2023/9/105019_0s.png)
python判断字符串的前两个字母是否是"id"的示例代码
2021-05-02 20:39:12
sql中返回参数的值
2024-01-29 11:29:00
在html中引入外部js文件,并调用带参函数的方法
2024-04-16 09:28:03
![](https://img.aspxhome.com/file/2023/3/136633_0s.jpg)
Python通过队列实现进程间通信详情
2023-07-24 17:49:44
![](https://img.aspxhome.com/file/2023/9/68939_0s.png)
Python 安装 virturalenv 虚拟环境的教程详解
2021-04-04 18:27:30
![](https://img.aspxhome.com/file/2023/1/124751_0s.png)
Python3操作SQL Server数据库(实例讲解)
2024-01-24 04:13:21
![](https://img.aspxhome.com/file/2023/3/121363_0s.png)
python+appium自动化测试之如何控制App的启动和退出
2023-06-24 12:45:01
![](https://img.aspxhome.com/file/2023/0/82910_0s.jpg)
网站中文字的视觉设计
2008-04-16 13:35:00
![](https://img.aspxhome.com/file/UploadPic/20084/16/2008416134135478s.jpg)
Python中new方法的详解
2022-12-06 14:20:18
Vue计时器的用法详解
2024-04-28 09:28:51
![](https://img.aspxhome.com/file/2023/0/132950_0s.jpg)
Pandas 数据处理,数据清洗详解
2022-05-23 16:04:23
深入学习python的yield和generator
2022-01-15 05:00:28
Python中交换两个元素的实现方法
2023-07-29 08:28:15
python实现稀疏矩阵示例代码
2023-10-03 02:37:18
![](https://img.aspxhome.com/file/2023/9/126889_0s.png)
基于Python PaddleSpeech实现语音文字处理
2023-04-26 19:14:42
![](https://img.aspxhome.com/file/2023/1/131321_0s.jpg)
pandas 像SQL一样使用WHERE IN查询条件说明
2023-07-01 23:26:37
![](https://img.aspxhome.com/file/2023/4/61724_0s.jpg)
解析ASP与SQL server互操作的时间处理
2008-05-17 11:57:00
Python利用pygame模块制作代码雨
2021-02-13 02:53:24
![](https://img.aspxhome.com/file/2023/3/76923_0s.png)