js利用闭包封装自定义模块的几种方法

1.自定义模块:

  具有特定功能的js文件

  将所有的数据和功能都封装在一个函数的内部

  只向外暴露一个包含有n个方法的对象或者函数

  模块使用者只需要通过模块暴露的对象调用方法来实现相对应的功能

1.利用函数方法自调用

/**
 * Created by lonecloud on 2017/9/10.
 */
(function (window) {
    var DEBUG="debug"
    /**
     * 打印日志
     * @param args
     */
    function log(args) {
        console.log(args)
    }

    /**
     * debug 利用闭包
     * @param args
     */
    function debug(args) {
        console.log(DEBUG+args);
    }
    /**
     * 编写
     * @param args
     */
    function write(args) {
        document.write(args)
    }
    window.$ = {
        log: log,
        write: write,
        debug:debug
    }
})(window);
//调用
$.write("dda")
$.debug("dsds")
$.log("dsqwd")

 2.函数声明后进行模块化

/**
 * Created by lonecloud on 2017/9/10.
 */
function Common(window) {
    var DEBUG = "debug"

    /**
     * 打印日志
     * @param args
     */
    function log(args) {
        console.log(args)
    }

    /**
     * debug 利用闭包
     * @param args
     */
    function debug(args) {
        console.log(DEBUG + args);
    }

    /**
     * 编写
     * @param args
     */
    function write(args) {
        document.write(args)
    }

    return {
        log: log,
        debug: debug,
        write: write
    }
}
//调用
var common=Common(window);
common.log("121")
common.debug(12232)
common.write("dadsa")

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值