当前位置:网站首页>分分钟理解原型模式
分分钟理解原型模式
2022-04-21 17:20:00 【掘金安东尼】
原型模式(Prototype Pattern)是用于创建重复的对象,同时又能保证性能。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。
这种模式是实现了一个原型接口,该接口用于创建当前对象的克隆。当直接创建对象的代价比较大时,则采用这种模式。
我们可以通过 JavaScript 特有的原型继承特性去实现原型模式,也就是创建一个对象作为另一个对象的 prototype 属性值,我们也可以通过 Object.create(prototype, optionalDescriptorObjects) 来实现原型继承。
Object.create() 方法会使用指定的原型对象及其属性去创建一个新的对象。
// 因为不是构造函数,所以不用大写
var
someCar
= {
drive:
function () { },
name:
'马自达 3'
};
// 使用Object.create创建一个新车x
var
anotherCar
=
Object.
create(
someCar);
console.
log(
anotherCar.
__proto__)
// {name: '马自达 3', drive: ƒ}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
如果 不直接使用 Object.create ,则模拟实现如下:
var
vehiclePrototype
= {
init:
function (
carModel) {
this.
model
=
carModel;
},
getModel:
function () {
console.
log(
'车:'
+
this.
model);
}
};
function
vehicle(
model) {
function
F() { };
F.
prototype
=
vehiclePrototype;
var
f
=
new
F();
f.
init(
model);
return
f;
}
var
car
=
vehicle(
'model 3');
car.
getModel();
console.
log()
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
把 car 打印出来看看,可看到其原型链;

小结:原型模式,就是创建一个共享的原型,通过拷贝这个原型来创建新的类,用于创建重复的对象,带来性能上的提升。要注意复制的深浅拷贝;
OK,以上就是本篇分享,你“学废”了吗?
我是掘金安东尼,输出暴露输入,技术洞见生活。
版权声明
本文为[掘金安东尼]所创,转载请带上原文链接,感谢
https://blog.51cto.com/u_13961087/5238467
边栏推荐
- Binary tree related creation or traversal
- idea装杯小技巧——实现鼠标滑动导包
- Fixturlaser对中仪维修GO/NXA Pro/ECO/EVO系列
- A simple and easy-to-use file upload scheme
- mysql为数据库表起别名的注意事项
- 2022 new air outlet! The tide of it crowd research is coming!!!
- 2022年北京购房攻略三 (政策篇)
- 我用Ehcache把查询性能提升了100倍,真香
- Control @ schedule on in different environments
- 1、 Overview of database system of database Series
猜你喜欢
随机推荐
The R language uses the grepl function to check whether the substring exists in the specified string and the string matches. It is responsible for searching whether the given string object contains a
【SOGAF】SOGAF架构类型/模式
824. Goat Latin
Using Jetson nano as an environmental weather station
CSP Darknet53
Image Manipulation Detection by Multi-View Multi-Scale Supervision
数字化时代,企业运维面临现状及挑战分析解读
@Transient
mysql创建数据库sql语句
WPF 引用 UWP 控件 不打包为 MSIX 分发的方法
Jira Seraph 中的身份验证绕过漏洞(CVE-2022-0540)
What is the "responsibility" of fault determination?
Quick MTF,镜头图像质量测试应用程序
关于内推想说的
R语言使用Hmisc包的label函数为dataframe中的特定变量(数据列)添加变量标签、将dataframe的数据列名称修改为数据说明标签、而通过数值索引访问dataframe数据列
MySQL primary key ID customization
OpenHarmony-UI框架适配层浅析(一)
域内信息查询工具AdFind
Vitis HLS build project and generate IP core (vivado HLS)
FastReport Business Graphics .NET









