1. Custom modules:
JS file with a specific function
Encapsulates all the data and functions inside a function
Exposes an object or function that contains n methods only outward
Module users only need to implement the corresponding function by invoking the method of the object exposed by the module.
1. Using the function method to self-invoke
/** * Created by Lonecloud on 2017/9/10. */(function (window) { var debug= "DEBUG" /** * Print log * @param args */ function log (args ) { Console.log (args) } /** * Debug using closures * @param args * /function debug (args) { Console.log (Debug+args); } /** * Write * @param args * /function write (args) { document.write (args) } window.$ = { Log:log, write:write, debug:debug }) (window);//Call $.write ("DDA") $.debug ("DSDs") $.log (" DSQWD ")
2. Modular after function declaration
/** * Created by Lonecloud on 2017/9/10. */function Common (window) { var debug = "Debug" /** * Print log * @param args * /function log (args) { console.log (args) } /** * Debug using closures * @param args * / function debug (args) { console.log (debug + args); } /** * Write * @param args * /function write (args) { document.write (args) } return { Log:log, debug:debug, write:write }}//call var common=common (window); Common.log ("121") Common.debug (12232) common.write ("DADSA")
Several methods of using closure package to customize module in JS