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())

 

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

// 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())

 

本文内容仅供个人学习、研究或参考使用,不构成任何形式的决策建议、专业指导或法律依据。未经授权,禁止任何单位或个人以商业售卖、虚假宣传、侵权传播等非学习研究目的使用本文内容。如需分享或转载,请保留原文来源信息,不得篡改、删减内容或侵犯相关权益。感谢您的理解与支持!

链接: https://shenqiku.cn/article/FLY_7880