原型模式
通俗点讲就是创建一个共享的原型,并通过拷贝这些原型创建新的对象
在我看来,其实原型模式就是指定新创建对象的模型,更通俗一点来说就是我想要新创建的对象的原型是我指定的对象。
最简单的原型模式的实现就是通过 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()函数,那么可以使用原型继承来实现:
function createObj(obj) {
function Fn() {}
Fn.prototype = obj
return new Fn()
}
const obj = {
value:1
}
const newObj = createObj(obj)
原型模式就是创建一个指定原型的对象。如果我们需要重复创建某个对象,那么就可以使用原型模式来实现。