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

构造器模式

如果我们系统中有多个员工,创建每一个员工都需要 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 类的写法同时兼顾了构造器模式和原型模式。

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

相关推荐
sxlishaobin2 小时前
设计模式之原型模式
设计模式·原型模式
范纹杉想快点毕业3 小时前
嵌入式通信核心架构:从状态机、环形队列到多协议融合
linux·运维·c语言·算法·设计模式
__万波__3 小时前
二十三种设计模式(二十)--解释器模式
java·设计模式·解释器模式
攀登的牵牛花4 小时前
前端向架构突围系列 - 架构方法(一):概述 4+1 视图模型
前端·设计模式·架构
雲墨款哥4 小时前
从一行好奇的代码说起:React的 useEffect 到底是不是生命周期?
前端·react.js·设计模式
cultivator1294806 小时前
设计原则和设计模式助记
设计模式
enjoy编程7 小时前
Spring boot 4 探究netty的关键知识点
spring boot·设计模式·reactor·netty·多线程
用户93816912553607 小时前
Head First 单例模式
后端·设计模式
a3535413828 小时前
设计模式-桥接模式
c++·设计模式·桥接模式
sxlishaobin8 小时前
设计模式之外观模式
java·设计模式·外观模式