• javascript 设计模式


    1.构造函数模式解释

    构造函数用来创建特定的实例,具有特定的参数属性和方法。

    2.代码解释

    1.基本构造函数

    function Person(sex, age, weight) {
        this.sex = sex
        this.age = age
        this.weight = weight
        this.say = function() {
            console.log(this.sex, this.age, this.weight)
        }
    }
    var xiaoming = new Person('男', 18, 60)
    var xiaohong = new Person('女', 18, 50)
    xiaoming.say()  //男 18 60
    xiaohong.say()  //女 18 50

    上述代码便是最基础的构造函数,通过new来构建一个实例,每个实例上面都有自己的属性和方法。

    上述实例公共方法可以提取一下,通过原型继承来实现

    2.改造构造函数

    function Person(sex, age, weight) {
        this.sex = sex
        this.age = age
        this.weight = weight
    }
    Person.prototype.say = function() {
        console.log(this.sex, this.age, this.weight)
    }
    var xiaoming = new Person('男', 18, 60)
    var xiaohong = new Person('女', 18, 50)
    xiaoming.say()   //男 18 60
    xiaohong.say()   //女 18 50

    通过简单的在原型上定义公共方法,每次构建实例不需要重新定义方法,节省内存,构建后的实例可以重原型上找到该方法的定义。其实可以在改进,如果这个构造函数没执行,那么也不需要在原型上定义方法。

    3.动态原型构造函数

    function Person(sex, age, weight) {
        this.sex = sex
        this.age = age
        this.weight = weight
        if(typeof Person._initFun === 'undefined') {
            Person.prototype.say = function() {
                console.log(this.sex, this.age, this.weight)
            }
            Person._initFun = true
        }
    }
    var xiaoming = new Person('男', 18, 60)
    var xiaohong = new Person('女', 18, 50)
    xiaoming.say()   //男 18 60
    xiaohong.say()   //女 18 50        

    该实现原来就是通过一个标志位判断是否是第一次构建实例,这样的好处是没有构建实例是不会在原型上定义方法,只有构建实例且第一次构建的时候才会在原型上定义方法。之后再构建实例便不会再次在原型上重复定义。

    4.强制new关键词

    我们知道构建词new能用来构建实例,如果不用new,this便会指向window,这样是不太好。所以改造一下构造函数

    function Person(sex, age, weight) {
        if (!(this instanceof Person)) {
            return new Person(sex, age, weight);
        }
        this.sex = sex
        this.age = age
        this.weight = weight
        if(typeof Person._initFun === 'undefined') {
            Person.prototype.say = function() {
                console.log(this.sex, this.age, this.weight)
            }
            Person._initFun = true
        }
    }
    var xiaoming = new Person('男', 18, 60)
    var xiaohong = Person('女', 18, 50)
    xiaoming.say()  //男 18 60
    xiaohong.say()  //女 18 50            

    构建实例首先会判断是否this对象的instanceof是否属于Person,如果不是则强制返回Person实例,否则执行下面的参数定义代码。

    end!!!

  • 相关阅读:
    解决SHAREJPOINT 跨域问题
    获取webpart方法以及连接字符串记录
    powerviot report cannot refresh data
    powerviot open error in sharepoint 2013
    Could not load file or assembly 'Microsoft.AnalysisServices.SharePoint.Integration'
    python 安装
    Git代码协作开发
    VScode操作文档
    python 模块定义、导入、优化
    hive替换文件中特殊字符
  • 原文地址:https://www.cnblogs.com/lyjfight/p/13920459.html
Copyright © 2020-2023  润新知