JavaScript设计模式-构造器模式

概念

  1. 在面向对象编程中,构造器是一个当新建对象的内存被分配后,用来初始化该对象的一个特殊函数。在JavaScript中几乎所有的东西都是对象,我们经常会对对象的构造器十分感兴趣。
  2. 对象构造器是被用来创建特殊类型的对象的,首先它要准备使用的对象,其次在对象初次被创建时,通过接收参数,构造器要用来对成员的属性和方法进行赋值

例子

这是一个构成器的经典写法:
第一步:定义一个对象,对象接受参数;
第二步:给对象的this挂载属性,也就是传入的参数赋值到this上;
第三步:给对象原型prototype 挂载方法
第四步:实例化对象并传入参数,也就是const order1 = new MyOrder(this.order1)

结果:经过上面步骤,实例化的order1 就拥有了price1 、price2 、date 这三个属性和sum 、getDate 方法。

		// 定义一个对象,这个对象接受一个order参数,order里面有三个参数:价格1、价格2、日期
        function MyOrder (order) {
            this.price1 = order.price1
            this.price2 = order.price2
            this.date = order.date
        }

        // Object.prototype ,以避免我们重新定义原型对象
        // 创建一算总价的方法,我们只需要 order1.sum() 这样,就能得出当前保单的总价
        MyOrder.prototype.sum = function () {
            return Number(this.price1) + Number(this.price2) + '元'
        }
        // 创建格式化日期的方法,我们只需要 order1.getDate() 这样,就能得统一格式的日期
        MyOrder.prototype.getDate = function () {
            const date =  new Date(this.date)
            return date.getFullYear() + '.' + (date.getMonth() + 1) + '.' + date.getDate()
        }

        // 使用:
        const order1 = new MyOrder(this.order1)
        const order2 = new MyOrder(this.order2)

        console.log('order1总价' + order1.sum())
        console.log('order2总价' + order2.sum())

        console.log('order1日期' + order1.getDate())
        console.log('order2日期' + order2.getDate())
        

ES6的构造器

ES6新增了Class类,每个class里都有一个constructor 构造函数,constructor 函数可以接收参数,
在我们new这个class的时候,constructor 会执行一遍并且接收new时传入的参数

        class classOrder {
            // 构造函数 new 的时候会执行一次 参数是你new的参数
            constructor (order) {
                this.price1 = order.price1
                this.price2 = order.price2
                this.date = order.date
            }
            sum() {
                return Number(this.price1) + Number(this.price2) + '元'
            }

            getDate() {
                const date =  new Date(this.date)
                return date.getFullYear() + '.' + (date.getMonth() + 1) + '.' + date.getDate()
            }
        }
        const order3 = new classOrder(this.order1)
        const order4 = new classOrder(this.order2)

        console.log('order3总价' + order3.sum())
        console.log('order4总价' + order4.sum())

        console.log('order3日期' + order3.getDate())
        console.log('order4日期' + order4.getDate())

总结

构造器模式就是在你实例化对象时,可以按照你传入的参数给对象添加属性和方法。可以让你实例化特殊的对象。

github仓库地址:点击 设计模式例子 查看

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值