原型模式 ⭐
定义
原型模式(Prototype Pattern),是用于创建对象的一种模式,通过克隆来创建对象的。
实现
js
const Plane = function () {
this.blood = 100
this.attackLevel = 1
this.defenseLevel = 1
}
const plane = new Plane()
plane.blood = 500
plane.attackLevel = 10
plane.defenseLevel = 7
const clonePlane = Object.create(plane)
console.log('*******clonePlane', clonePlane)
console.log('*******plane', plane)
console.log(
'------clonePlane getOwnPropertyDescriptors',
Object.getOwnPropertyDescriptors(clonePlane),
)
console.log(
'------plane getOwnPropertyDescriptors',
Object.getOwnPropertyDescriptors(plane),
)
js
function CustomerPrototype(proto) {
this.proto = proto
this.clone = function () {
var customer = new Customer()
customer.first = proto.first
customer.last = proto.last
customer.status = proto.status
return customer
}
}
function Customer(first, last, status) {
this.first = first
this.last = last
this.status = status
this.say = function () {
console.log(
'name: ' +
this.first +
' ' +
this.last +
', status: ' +
this.status,
)
}
}
const proto = new Customer('n/a', 'n/a', 'pending')
const prototype = new CustomerPrototype(proto)
const customer = prototype.clone()
customer.say()
console.log('*******proto', proto)
console.log('*******customer', customer)
console.log(
'------proto getOwnPropertyDescriptors',
Object.getOwnPropertyDescriptors(proto),
)
console.log(
'------customer getOwnPropertyDescriptors',
Object.getOwnPropertyDescriptors(customer),
)