码迷,mamicode.com
首页 > Web开发 > 详细

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

时间:2017-09-10 11:26:30      阅读:241      评论:0      收藏:0      [点我收藏+]

标签:利用   nbsp   rgs   调用   封装   sds   ted   包含   console   

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

 

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

标签:利用   nbsp   rgs   调用   封装   sds   ted   包含   console   

原文地址:http://www.cnblogs.com/lonecloud/p/7500340.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!