【设计模式】构造器模式和原型模式

构造器模式

如果我们系统中有多个员工,创建每一个员工都需要 new 一下,出现很多重复代码,所以我们可以将他们写成一个构造函数,然后通过传入的不同参数创建不同的员工。

js 复制代码
function Employee(name, age) {
    this.name = name
    this.age = age
    this.toString = function() {
        return `name: ${this.name}, age: ${this.age}`
    }
}

const employee1 = new Employee('张三', 18)
console.log("=>(index.js:7) employee1", employee1); 
//=>(index.js:7) employee1 Employee { name: '张三', age: 18, toString: [Function (anonymous)] }

原型模式

以上代码中toString 方法,每次 new 一个对象都需要重新创建一个,而这个方法却是每一个 Employee 共有的,所以能不能把这个方法提取到一个公共的地方捏?

此时就需要我们使用原型模式,将 toString 方法挂载到 Employee 的原型上。

js 复制代码
function Employee(name, age) {
    this.name = name
    this.age = age
}

Employee.prototype.toString = function () {
    return `name: ${this.name}, age: ${this.age}`
}

const employee1 = new Employee('张三', 18)
console.log("=>(index.js:7) employee1", employee1);
//=>(index.js:7) employee1 Employee { name: '张三', age: 18 }
console.log(employee1.toString())
// name: 张三, age: 18

那假如我们使用 ES6 写法呢?

js 复制代码
class Employee {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }

    toString() {
        return `name: ${this.name}, age: ${this.age}`
    }
}
const employee1 = new Employee('张三', 18)
console.log("=>(index.js:7) employee1", employee1);
//=>(index.js:7) employee1 Employee { name: '张三', age: 18 }
console.log(employee1.toString())
// name: 张三, age: 18

很神奇!toString 直接被挂载到原型上!

所以说,es6 类的写法同时兼顾了构造器模式和原型模式。

应用场景有比如组件的复用,状态管理等。

相关推荐
Tt有了t18 小时前
设计模式速查
java·python·设计模式
一条Go19 小时前
四个进程,一把锁:Alioth 的告警评测为什么不需要消息队列
后端·设计模式·架构
一缕82年的清风1 天前
被中产唾弃的“十元快剪”,藏着最狠的极客工程学
人工智能·设计模式
是2的10次方啊1 天前
设计模式与生活⑫:周报又到手,别从空白开始
设计模式
拆房老料2 天前
DeepSeek Super-agent 架构解析:从单任务 Agent 到持续运行的任务系统
人工智能·设计模式·系统架构
工一木子2 天前
设计模式与生活⑩:地铁没变,你换了个状态
设计模式
是2的10次方啊2 天前
设计模式与生活⑪:地铁里被打扰,别总靠自己硬扛
设计模式
高晶2 天前
SPMI 控制器 RTL 设计与验证新手入门
设计模式·程序员·架构
geovindu3 天前
rust:N-Barrier Pattern
开发语言·后端·设计模式·rust·屏障模式·并发型模式
顧棟3 天前
OpenAPI 网关:鉴权 + 流量治理 一体化设计方案与实现
java·spring boot·设计模式