zoukankan      html  css  js  c++  java
  • 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")
    
  • 相关阅读:
    新词发现
    隐马尔可夫模型
    nodejs命令行解析工具之minimist
    react 生命周期
    react 中的 super super(props)
    object 常用方法总结
    前端安全 中间人攻击
    Postgresql的临时表的用法
    windows下postgresql数据库备份和还原
    PostgreSQL 数据库开发规范——命名规范 & 设计规范
  • 原文地址:https://www.cnblogs.com/lonecloud/p/7500340.html
Copyright © 2011-2022 走看看