闭包的应用-定义js模块

107 阅读1分钟

1定义js模块

function myModule(){
    var msg = 'xiaozhan';
    //定义闭包
    function dosomething(){
        console.log(msg);
    }
    function doothersomthing(){
        return msg;
    }
    return {dosomething:dosomething,doothersomthing:doothersomthing};
}
//调用
var mymodule = myModule();
mymodule.dosomething();
cobnsole.log(mymodule.doothersomthing);

2 将函数内部的对象挂载到全局上

(function myModule(w){
    var msg = 'xiaozhan';
    //定义闭包
    function dosomething(){
        console.log(msg);
    }
    function doothersomthing(){
        return msg;
    }
    w.myobj={
        dosomething:dosomething,
        doothersomthing:doothersomthing
    };
})(window)
mymoduleObj2.dosomething();
console.log(mymoduleObj2.doOtherthing());

image.png