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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM