原型模式 ⭐
定义
原型模式(Prototype Pattern):通过复制/克隆已有对象来创建新对象,而不是通过 new 构造。
在其他语言中,原型模式是一种需要刻意引入的设计模式,用来解决 new 实例化性能差的问题;但在 JavaScript 中,原型模式不仅是设计模式,更是语言的核心基础。
从 Object.create() 到原型链继承,再到业务中常用的深浅拷贝生成配置对象,可以说前端开发无时无刻不在践行原型模式的思想。
实现与案例
1. Object.create()
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),
)
2. 深拷贝克隆
js
class DocumentTemplate {
constructor() {
this.title = "未命名";
this.content =[];
this.metadata = { author: "Admin", timestamp: Date.now() };
}
// 现代前端常用的克隆方法(深拷贝)
clone() {
// 使用现代浏览器原生的 deep clone API
return structuredClone(this);
// 或者传统的 JSON.parse(JSON.stringify(this))
}
}
const defaultDoc = new DocumentTemplate();
const myDoc = defaultDoc.clone();
myDoc.title = "前端架构设计";
myDoc.metadata.author = "张三"; // 修改深层对象,不会影响母体 defaultDoc
前端应用场景
1. JavaScript 的原型链机制
这是原型模式最伟大的应用。JS 中几乎所有的对象创建,本质上都是原型模式。
当我们写下 const arr = [1, 2, 3] 时,其实就是在克隆/委托 Array.prototype 这个对象。数组能使用 push、map 等方法,并不是因为你的 arr 自己实现了这些方法,而是它作为克隆体,在顺着原型链寻找“母体”身上的能力。
2. 配置对象复用
js
// 默认配置(原型)
const defaultAxiosConfig = {
method: 'GET',
timeout: 5000,
headers: { 'Content-Type': 'application/json' }
};
function request(url, userConfig) {
// 结合展开运算符,本质上就是在拷贝原型并覆盖新属性
const finalConfig = { ...defaultAxiosConfig, ...userConfig };
// ...
}
3. React / Vue 状态不可变
js
setState(prev => ({
...prev,
count: prev.count + 1
}))