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")
    
  • 相关阅读:
    touch
    ls
    Linux基础
    errors
    strconv
    strings
    fmt
    os/exec
    笔记本连不上网怎么办
    笔记本连不上网怎么办
  • 原文地址:https://www.cnblogs.com/lonecloud/p/7500340.html
Copyright © 2011-2022 走看看