前端设计模式——原型模式

原型模式

原型模式:通俗点讲就是创建一个共享的原型,并通过拷贝这些原型创建新的对象。

在我看来,其实原型模式就是指定新创建对象的模型,更通俗一点来说就是我想要新创建的对象的原型是我指定的对象。

最简单的原型模式的实现就是通过Object.create()。Object.create(),会使用现有的对象来提供新创建的对象的__proto__。

let person = {
  name:'hello',
  age:24
}

let anotherPerson = Object.create(person);
console.log(anotherPerson.__proto__)  //{name: "hello", age: 24}

anotherPerson.name = 'world';  //可以修改属性
anotherPerson.job = 'teacher';

上面的代码使用Object.create()将person对象作为anotherPerson对象的原型,创建了anotherPerson。因此anotherPerson可以直接获得person的属性name,age等。

另外,如果我们想要自己实现原型模式,而不是使用封装好的Object.create()函数,那么可以使用原型继承来实现

function F(){
}
F.prototype.g = function(){}

//G类继承F类

function G(){
  F.call(this);
}

//原型继承
function Fn(){}
Fn.prototype = F.prototype;
G.prototype = new Fn();

G.prototype.constructor = G;

上面的代码,学过js的应该都能看懂,没什么好解释的。
原型模式总结
原型模式就是创建一个指定原型的对象。如果我们需要重复创建某个对象,那么就可以使用原型模式来实现。

posted @ 2019-04-28 09:38  海因斯坦  阅读(1269)  评论(0编辑  收藏  举报