閉包 ,自執行函數有啥作用呢?

自執行函數作用:js是函數作用域,防止變量污染; 

閉包作用:函數外可以訪問函數內變量;



下面來附上一段項目中代碼來說明;

;
dynews.TvEditSystem = (function ($, window, document) {
    var mainGuid = getRequestByName("mainGuid");
    var mainColumnId = "";
    var thisContext;
    var index = 0;
    var ue;
    var privilegeIds = window.parent.sessionStorage.getItem("privilegeIds");
    var Regexs; //定義驗證各種格式類型的正則表達式對象
    var lockMsg;
    // 欄目下拉數據,這些數據外部函數無法訪問,return中可以,閉包。
    var userId = window.parent.sessionStorage.getItem("userId");//提交時和稿件創建了比較,
    var userColumnIds = window.sessionStorage.getItem(dynews.global.userColumnIds);
    var allColumnIds = window.sessionStorage.getItem(dynews.global.allColumnIds);
    var CFBFlag = window.parent.sessionStorage.getItem("CFBFlag");

    var configGuid;
    var basicInfoShowItems = [];
    var basicInfoAllItems = [];
    // 記錄開關的值start
    var tvVideoLengthVal = 0;
    var tvBroadLengthVal = 0;
    var tvEstimateLengthVal = 0;
    // 記錄開關的值end
    var tvIsManualBroadVideoFlag = 0;// 視頻和口播是否手動flag
    var tvEstimateLengthFlag=0;//擬播長度時候手動flag;

    return {
        init: function () {
            thisContext = this;
            thisContext.initViewStyle();
            thisContext.initEvent();
            thisContext.initUeditor();
            // 通過配置初始化基本信息(部分)
            thisContext.initBasicInfoByConfig();
            //初始化配置彈框(all);
            thisContext.initSelectConfig();
            Regexs = {
                audio: (/\.(mp3|wav|wma)$/i),//音頻格式
                word: (/\.(doc|docx)$/i),//word格式
                image: (/\.jpg$|\.jpeg$|\.gif$/i)// 圖片格式
            };

        },

        initBasicInfoByConfig: function () {
        	$('.manuLoader').show();
            var userId = window.sessionStorage.getItem('userId');
            var datalist = {
                userId: userId,
                userConfigType: '202'
            }
            topUtil.ajaxRequest({
                type: "post",
                async: false,
                //contentType: "application/json;charset=UTF-8",
                dataType: "json",
                url: dynews.global.dynewsPath + "UserConfigController/getUserConfigInfo",
                //data: JSON.stringify(datalist),
                data: datalist,
                success: function (data) {
                    if (data.status) {
						/*if(window.sessionStorage.getItem('firstConfigValue') == null || window.sessionStorage.getItem('firstConfigValue') == ' '){
							window.sessionStorage.setItem('firstConfigValue',data.data.userConfigValue);
						}*/
                        var tvList = JSON.parse(data.data.userConfigValue)
                        configGuid = data.data.userConfigGuid;
                        var basicInfoConfigTemp = template('basicInfoConfigTemp', tvList);
                        $('#basicInfoConfig').html("");
                        $('#basicInfoConfig').html(basicInfoConfigTemp);
                        $("#mainSummary").off('keyup').on('keyup', function () {
            				thisContext.checkWordLength($(this));
            			});
                        $("#mainKeyWords").off('keyup').on('keyup', function () {
            				thisContext.checkWordLength($(this));
            			});
                        $("#edit_title").off('keyup').on('keyup', function () {
            				thisContext.checkWordLength($(this));
            			});
                        $("#tvSubtitle").off('keyup').on('keyup', function () {
            				thisContext.checkWordLength($(this));
            			});
                        basicInfoShowItems = tvList.tvInfo;

                        // 初始化下拉組件;
                        console.log("-------基本信息---這是部分------")
                        console.log(basicInfoShowItems);
                        thisContext.initPullDownSelect(tvList.tvInfo)
                        // 刷新所有下拉組件
                        $("#basicInfoConfig select").selectpicker('refresh');
                        // 初始化datepicker
                        $("#tvEstimateTime").datepicker({
                            autoclose: true,
                            todayHighlight: true,
                            language: "zh-CN",/* --語言設置*/
                            format: "yyyy-mm-dd"  /*--日期顯示格式*/
                        });
                        // 初始化開關按鈕(源碼中的方法)
                        $(function () {
                            honeySwitch.init();
                        });
                        setTimeout(function () {
                            thisContext.showHoneySwitch();
                            thisContext.initData();
                        })
                    } else {
                        alert(data.msg);
                    }
                }
            });
        },
        // 初始化下拉組件
        initPullDownSelect: function (tvList) {

        },
        
        /**
		 * 對稿件的定時器進行初始化
		 */
		initSaveAuto : function(origin){

		},
        

        //初始化配置彈框;
        initSelectConfig: function () {
            var datalist = {
                userId: userId,
                sysConfigType: '107'
            }
            topUtil.ajaxRequest({
                type: "post",
                async: false,
                //contentType: "application/json;charset=UTF-8",
                dataType: "json",
                url: dynews.global.dynewsPath + "SysConfigController/getSysConfigInfo",
                //data: JSON.stringify(datalist),
                data: datalist,
                success: function (data) {
                 
                }
            });
        },

        /**
         * 初始化頁面視圖style 
         */
        initViewStyle: function () {
            $('.editHeight').css('height', $(".editFluid").height() - 180 + 'px');
            $('.cont_right').css('height', $('.editFluid').height() - 84 + 'px');
            $('#info_basic').css('height', $('.tabbable-custom').height() - 43 + 'px');
            $('.otherfile_lists').css('height', $('.tabbable-custom').height() - 98 - 234 + 'px');
            $('.checkCont .message_cont').css('height', $('.checkCont').height() - 80 + 'px');

        },

        /**
         * 初始化數據,通過mainGuid獲取後臺數據展示到頁面中;
        */
        initData: function () {
            var externalManuscript = JSON.parse(window.top.sessionStorage.getItem("externalManuscript"));
            if (mainGuid) {
                thisContext.loadInfo(mainGuid);
                // 初始化附件列表
                thisContext.initAttachment();
            } else if (topUtil.isNotEmpty(externalManuscript)) {
                mainCreateUserId = window.sessionStorage.getItem("userId");
                debugger;
                thisContext.loadDefaultInfo();
                thisContext.initManuscriptObj();
                thisContext.initExternal(externalManuscript);
            } else {
                thisContext.loadDefaultInfo();
                thisContext.initManuscriptObj();
                $("#tvSpeed").on("change", thisContext.ueChangeCallback);
                mainCreateUserId = window.sessionStorage.getItem("userId");
                $('.manuLoader').hide();
            }
            //初始化標籤列表
            thisContext.initTagList();
        },
        
        
        
        /**
         * 刪除附件
         * @param maGuid
         * @returns
         */
        deleteAttach : function(event,maGuid){
            event.stopPropagation();
        	var postData = {
        		maGuid : maGuid,
        	}
        	topUtil.ajaxRequest({
                type: "post",
                async: true,
                dataType: "json",
                url: dynews.global.dynewsPath + "ManuscriptAttachmentController/deleteManuscriptAttachment",
                data: postData,
                success: function (data) {
                    if (data.status) {
                    	$("#myVideo").attr('src',"");
                    	thisContext.initAttachment();
                        $.notify("附件刪除成功!");
                    } else {
                    	$.notify("附件刪除失敗!");
                    }
                }
            });
        },


  
        empty: null
    }
})(jQuery, window, document);


   1.,我們爲了不讓外面變量污染下面這一系列的變量。所以使用自自執行函數。

    var mainGuid = getRequestByName("mainGuid");
    var mainColumnId = "";
    var thisContext;
    var index = 0;
    var ue;
    var privilegeIds = window.parent.sessionStorage.getItem("privilegeIds");
    var Regexs; //定義驗證各種格式類型的正則表達式對象
    var lockMsg;

2,但是,雖然不污染了,但是js是函數作用域,在自執行函數外面無法訪問函數內的的內容。所有我們就得用閉包來實現;

總結:所以使用自執行函數和閉包就是爲了解決問題:

即 既不會發生變量污染(函數外面變量不會覆蓋函數內部變量)而且 也可以在外面訪問到函數內部變量

在說明下:(jQuery, window, document)可寫可不寫,因爲函數內可以訪問函數外變量。但是寫上之後比較好吧

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章