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