• JS 原生闭包模块化开发总结


    一、闭包模块的第一种写法:

    // HH: 闭包类的第一种写法
    var PeopleClass = function () {
        var age = 18
        var name = 'HAVENT'
    
        // 闭包返回公开对象
        return {
            getAge: function () {
                return age
            },
            getName: function () {
                return name
            }
    
        }
    }
    
    // HH: 闭包类的第一种写法的调用
    var people = new PeopleClass()
    console.log(people.getAge())
    console.log(people.getName())

    二、闭包模式的第二种写法

    // HH: 闭包类的第二种写法
    var PeopleClass = function () {
        var main = {}
        var age = 18
        var name = 'HAVENT'
        
        main.getAge = function () {
            return age
        }
        
        main.getName = function () {
            return name
        }
    
        // 闭包返回公开对象
        return main
    }
    
    // HH: 闭包类的第二种写法的调用
    var people = new PeopleClass()
    console.log(people.getAge())
    console.log(people.getName())

    三、闭包模式的自动实例化对象的写法

    // HH: 闭包类的自动实例化对象的写法
    var we = we || {}
    we.people = (function () {
        var age = 18
        var name = 'HAVENT'
    
        function getPeopleAge () {
            return age
        }
    
        function getPeopleName() {
            return name
        }
    
        // 闭包返回公开对象
        return {
            getAge: function () {
                return getPeopleAge()
            },
            getName: function () {
                return getPeopleName()
            }
        }
    })()
    
    // HH: 闭包类的自动实例化对象的写法的调用
    console.log(we.people.getAge())
    console.log(we.people.getName())

    广州品牌设计公司https://www.houdianzi.com PPT模板下载大全https://redbox.wode007.com

    四、闭包类的方法注入模式写法

    // HH: 闭包类的方法注入模式写法
    var we = we || {}
    we.people = function () {
        this.age = 18
        this.name = 'HAVENT'
    }
    
    we.people.prototype.getAge = function () {
        return this.age
    }
    
    we.people.prototype.getName = function () {
        return this.name
    }
    
    // HH: 闭包类的方法注入模式写法的调用
    var people = new we.people()
    console.log(people.getAge())
    console.log(people.getName())
  • 相关阅读:
    [CF920E] Connected Components?
    [CF981E] Addition on Segments
    [BZOJ2152] 聪聪可可
    [CF1355E] Restorer Distance
    [CF1101D] GCD Counting
    [CF827C] DNA Evolution
    [HNOI2008] 明明的烦恼
    [CF712D] Memory and Scores
    [CF609E] Minimum spanning tree for each edge
    后缀自动机应用小结 I
  • 原文地址:https://www.cnblogs.com/qianxiaox/p/14085727.html
Copyright © 2020-2023  润新知