7

分分钟理解原型模式

 2 years ago
source link: https://blog.51cto.com/u_13961087/5238467
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

分分钟理解原型模式

原创

掘金安东尼 2022-04-21 15:35:07 ©著作权

文章标签 原型模式 创建对象 原型继承 文章分类 JavaScript 前端开发 阅读数182

原型模式(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: ƒ}

如果 不直接使用 ​​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()

把 car 打印出来看看,可看到其原型链;

分分钟理解原型模式_原型模式

小结:原型模式,就是创建一个共享的原型,通过拷贝这个原型来创建新的类,用于创建重复的对象,带来性能上的提升。要注意复制的深浅拷贝;

OK,以上就是本篇分享,你“学废”了吗?

 我是掘金安东尼,输出暴露输入,技术洞见生活。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK