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

构造器模式

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

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

相关推荐
廋到被风吹走15 小时前
【Java】常用设计模式及应用场景详解
java·开发语言·设计模式
Jaycee青橙18 小时前
软件设计模式详解
设计模式
alibli21 小时前
一文学会设计模式之结构型模式及最佳实现
c++·设计模式
电子科技圈1 天前
SiFive车规级RISC-V IP获IAR最新版嵌入式开发工具全面支持,加速汽车电子创新
嵌入式硬件·tcp/ip·设计模式·汽车·代码规范·risc-v·代码复审
七月丶1 天前
Cloudflare 🌏 中国大陆网络访问优化 - 0元成本
人工智能·react.js·设计模式
筏.k1 天前
C++ 设计模式系列:单例模式
c++·单例模式·设计模式
__万波__1 天前
二十三种设计模式(十二)--代理模式
java·设计模式·代理模式
郝学胜-神的一滴1 天前
Linux线程编程:从原理到实践
linux·服务器·开发语言·c++·程序人生·设计模式·软件工程
我爱学习_zwj1 天前
前端设计模式:轻量级实战指南
设计模式·前端框架·状态模式
还是大剑师兰特1 天前
前端设计模式:详解、应用场景与核心对比
前端·设计模式·大剑师