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

 

posted @ 2017-09-10 10:25  lonecloud  阅读(2029)  评论(0编辑  收藏  举报
我的博客即将同步至 OSCHINA 社区,这是我的 OSCHINA ID:lonecloud,邀请大家一同入驻:https://www.oschina.net/sharing-plan/apply