利用js的闭包原理做对象封装及调用方法

创建一个js文件,名为testClosure.js:

(function () {
  function a()
  {
    alert('i am a');
  }
  outFunc = function () {
    a();
  }
})();

这里不论写多少个function,a b c d ...外面都调用不到,包括这里面var定义的变量也都调用不到,那么你在里面尽情的写,就不用担心这些函数名变量名跟外界冲突;

只需要暴露一个outFunc这个函数供外界调用。这个函数呢没有用var定义,就变成一个全局变量,外界就可以调用的到,利用这一点,让这个函数变成匿名函数和外界沟通的桥梁。

再利用js面向对象的方法,就可以封装出非常好用的组件。

示例一:不需要继承的js组件

(function()
{
  var arrAuthItem = new Array();
  var isInited = false;
  var syncTableObj=findObj("sync-table-id",document);

  var newTR=null;
 var checkBox=null;
 var authTable = null;
 var selfPicUrl=null;
 var selfItem=null;

 var isAuthItemEnabled=false;
  var isSelfItemEnabled=false;

  function getAuthShopCurrent()
  {
   return $("#"+globalSyncVars.serverComClientId.AuthShopListId).val();
  }

  function getSyncFieldCurrent()
  {
   return $("#"+globalSyncVars.serverComClientId.SyncFieldListId).val();
  }

  function setTitle()
  {
   $("#sync-table-title-id").html("从“"+getAuthShopCurrent()+"”同步");
  }

  function getNumIidFrom(numIidTo)
  {
     var curRowData = jQuery("#listItemDefine").jqGrid('getRowData', numIidTo);
     return curRowData.NumIidFrom;
  }

  function insertRows()
  {
   deleteAll();

   for(var i=0;i<arrAuthItem[getAuthShopCurrent()+getSyncFieldCurrent()+""].length;i++)
   {
   newTR=syncTableObj.insertRow(syncTableObj.rows.length);
   // 0 checkbox
   checkBox=newTR.insertCell(0);
   // 1 auth table
   authTable=newTR.insertCell(1);
   // 2 self picurl
   selfPicUrl=newTR.insertCell(2);
   // 3 self item
   selfItem=newTR.insertCell(3);

   isSelfItemEnabled=setterSelfItem(i);
   isAuthItemEnabled=setterAuthItem(i);

   if(isAuthItemEnabled&&isSelfItemEnabled)
    setterEnableStatus(true,i);
   else
    setterEnableStatus(false,i);
   }
  }

  function setterAuthItem(i)
  {
   var isEnabled=false;

   if (!stringToBoolean(arrAuthItem[getAuthShopCurrent()+getSyncFieldCurrent()+""][i]["HasSameItem"]))
 {
  authTable.innerHTML='<table class="inner-table-class inner-table-from-class"><tr><td class="inner-table-td-radio-class"></td><td class="inner-table-td-class main-img-class"></td><td class="inner-table-td-class" style="padding-top:21px;padding-bottom:21px;">此宝贝没有对应的授权宝贝</td><td class="inner-table-td-class sync-img-class"><span class="icon-no-class"/></td></tr></table>';
  return isEnabled;
 }

 var arr = arrAuthItem[getAuthShopCurrent()+getSyncFieldCurrent()+""][i]["ListItemFrom"];
 var strHead = '<table class="inner-table-class inner-table-from-class">';
 var strTr = "";
 var isBinded = false;

 // 如果已经绑定了,标记一下,是否已经授权过也标记
    var numIid = getNumIidFrom(arrAuthItem[getAuthShopCurrent()+getSyncFieldCurrent()+""][i]["NumIidTo"]);
    if(numIid!="none")
    {
      for(var j=0;j<arr.length;j++)
      {
        if(arr[j]["NumIid"]==numIid)
        {
          isBinded=true;
          break;
        }
      }
    }

 for(var p=0;p<arr.length;p++)
 {
  var isSharedFrom = stringToBoolean(arr[p]["IsFromItemHasShareFrom"]);
  var isSharedTo = stringToBoolean(arr[p]["IsFromItemHasShareTo"]);
  var picUrl='<a href="http://item.taobao.com/item.htm?id=' + arr[p][" rel="external nofollow" NumIid"] + '" target="_blank"><img class="icon" style="padding:0px;width:60px" src="' + arr[p]["PicUrl"] + '_sum.jpg" title="' + arr[p]["Title"] + '" /></a>';
  if(getEnabledStatus(isBinded,!isSharedTo,isSelfItemEnabled))
  isEnabled = true;
  strTr+='<tr><td class="inner-table-td-radio-class">'+getRadioCode(isBinded,!isSharedTo,isSelfItemEnabled,i,arr.length)+'</td><td class="inner-table-td-class main-img-class">'+picUrl+'</td><td class="inner-table-td-class">'+getAuthItemCode(arr[p],isSharedFrom,isSharedTo,i)+'</td><td class="inner-table-td-class sync-img-class">'+getEnabledCode(isBinded,!isSharedTo,isSelfItemEnabled,arr[p],numIid)+'</td></tr>';
 }
 authTable.innerHTML = strHead+strTr+'</table>';
 return isEnabled;
  }
  // 返回auth宝贝详情html代码
  function getAuthItemCode(obj,isSharedFrom,isSharedTo,i)
  {
   var labelStr = "";
   if(isSharedFrom) labelStr = '<span style="color:red;">【源】</span>';
   if(isSharedTo) labelStr = '<span style="color:red;">【受】</span>';
   return '<span style="line-height:20px;" columnName="NumIid">'+labelStr+'ID:' + obj["NumIid"] + '</span>'
       + '<span style="padding-left:14px;" columnName="OuterId">商家编码:' + obj["OuterId"] + '</span>'
       + '<span style="padding-left:14px;color:'+getPriceColor(obj["Price"],i)+'" columnName="Price">价格:' + obj["Price"] + '</span>'
       + '<br><span style="line-height:20px;" columnName="Title">' + obj["Title"] + '</span>';
  }
  // 返回self宝贝详情html代码
  function getSelfItemCode(obj)
  {
   var labelStr = "";
   if(stringToBoolean(obj["IsToItemHasShareFrom"])) labelStr = '<span style="color:red;">【源】</span>';
   if(stringToBoolean(obj["IsToItemHasShareTo"])) labelStr = '<span style="color:red;">【受】</span>';
   return '<span class="sync-table-td-class"><span style="line-height:20px;" columnName="NumIid">'+labelStr+'ID:' + obj["NumIidTo"] + '</span>'
       + '<span style="padding-left:14px;" columnName="OuterId">商家编码:' + obj["OuterIdTo"] + '</span>'
       + '<span style="padding-left:14px;color:black;" columnName="Price">价格:' + obj["PriceTo"] + '</span></span>'
       + '<br><span class="sync-table-td-class" style="line-height:20px;" columnName="Title">' + obj["TitleTo"] + '</span>';
  }
  // 返回绑定关系图标的html代码
  function getEnabledCode(isBinded,isAuthEnabled,isSelfEnabled,obj,numIid)
  {
   if(isBinded)
   {
      // 如果是绑定状态,还要看当前item是否为绑定的item
      // 在这种情况下,判断是否可绑定,不需要用到selfItem
      if(obj["NumIid"]==numIid)
        return '<span class="icon-bind-class"/>';
      else
      {
        if(stringToBoolean(obj["IsFromItemHasShareTo"]))
          return '<span class="icon-no-class"/>';
        else
          return '<span class="icon-ok-class"/>';
      }
   }else
   {
   if(isAuthEnabled&&isSelfEnabled)
    return '<span class="icon-ok-class"/>';
   else
    return '<span class="icon-no-class"/>';
   }
  }
  // 是否可以绑定
  function getEnabledStatus(isBinded,isAuthEnabled,isSelfEnabled)
  {
   if(isBinded) return false;
   if(isAuthEnabled&&isSelfEnabled)
    {
   return true;
    }
   else
    {
   return false;
    }
  }
  // 返回radio的html代码
  /**
  *  isBinded 是否已经绑定
  *  isAuthEnabled auth是否可同步
  *  isSelfEnabled self是否可同步
  *  当前rows的index
  *  当前auth-list的长度(如果是一对一,当然不需要radio)
  */
  function getRadioCode(isBinded,isAuthEnabled,isSelfEnabled,i,length)
  {
   if(isBinded) return "";
    if(length==1) return "";
   if(isAuthEnabled==false||isSelfEnabled==false) return "";
 return '<input type="radio" name="radio'+i+'">';
  }

  function setterSelfItem(i)
  {
   var isEnabled=true;
   var picUrl='<a href="http://item.taobao.com/item.htm?id=' + arrAuthItem[getAuthShopCurrent()+getSyncFieldCurrent()+" rel="external nofollow" "][i]["NumIidTo"] + '" target="_blank"><img class="icon" style="padding-left:11px;width:60px" src="' + arrAuthItem[getAuthShopCurrent()+getSyncFieldCurrent()+""][i]["PicUrlTo"] + '_sum.jpg" title="' + arrAuthItem[getAuthShopCurrent()+getSyncFieldCurrent()+""][i]["TitleTo"] + '" /></a>';

   selfPicUrl.innerHTML = picUrl;
   selfItem.innerHTML = getSelfItemCode(arrAuthItem[getAuthShopCurrent()+getSyncFieldCurrent()+""][i]);

   if(stringToBoolean(arrAuthItem[getAuthShopCurrent()+getSyncFieldCurrent()+""][i]["IsToItemHasShareFrom"])) isEnabled = false;
   if(stringToBoolean(arrAuthItem[getAuthShopCurrent()+getSyncFieldCurrent()+""][i]["IsToItemHasShareTo"])) isEnabled = false;
   return isEnabled;
  }

  function getPriceColor(price,i)
  {
   if(arrAuthItem[getAuthShopCurrent()+getSyncFieldCurrent()+""][i]["PriceTo"]==undefined) return "black";
   if(price==undefined) return "black";
   return (price==arrAuthItem[getAuthShopCurrent()+getSyncFieldCurrent()+""][i]["PriceTo"])?"black":"red";
  }

  function setterEnableStatus(isEnabled,i)
  {
   if(isEnabled)
   checkBox.innerHTML='<input class="enableCheckbox" type="checkbox" checked="checked" index="'+i+'"/>';
   else
   checkBox.innerHTML='<input type="checkbox" disabled="true"/>';
  }

  function stringToBoolean(str)
  {
   if (str==undefined) return false;
   switch(str.toLowerCase())
   {
   case "true": case "yes": case "1": return true;
   case "false": case "no": case "0": case null: return false;
   default: return Boolean(str);
   }
  }

  function deleteAll()
  {
   for(var i=syncTableObj.rows.length-1;i>2;i--)
   {
   syncTableObj.deleteRow(i);
   }
  }

  function selectAll(isSelect)
  {
   if(isSelect)
   {
   $(".enableCheckbox").prop("checked",true);
   }else
   {
   $(".enableCheckbox").prop("checked",false);
   }
  }

  function findObj(theObj, theDoc)
 {
 var p, i, foundObj;
 if(!theDoc) theDoc = document;
 if((p = theObj.indexOf("?")) > 0 && parent.frames.length)
 {
  theDoc = parent.frames[theObj.substring(p+1)].document;
  theObj = theObj.substring(0,p);
 }
 if(!(foundObj = theDoc[theObj]) && theDoc.all)
 foundObj = theDoc.all[theObj];
 for (i=0; !foundObj && i < theDoc.forms.length; i++)
  foundObj = theDoc.forms[i][theObj];
 for(i=0; !foundObj && theDoc.layers && i < theDoc.layers.length; i++)
  foundObj = findObj(theObj,theDoc.layers[i].document);
 if(!foundObj && document.getElementById)
  foundObj = document.getElementById(theObj);
 return foundObj;
 } 

 function refrash()
 {
 deleteAll();

 if(!isInited)
  return; 

 setTitle();

 //现在js还没有数据的,去取值
 if(arrAuthItem[getAuthShopCurrent()+getSyncFieldCurrent()+""]==null)
 {
  var urledit="./x.aspx?method=GetAuthItem&rmd="+Math.random();
  $.post(urledit,$("#"+globalSyncVars.serverComClientId.form1).serialize())
  .done(function(myJsonResult) {
       var data = $.evalJSON(myJsonResult);
       ajaxResponseResult(data);
       if (data.IsSuccess) {
         arrAuthItem[getAuthShopCurrent()+getSyncFieldCurrent()+""]=data.rows;
         insertRows();
         $("#sync-table-id").css("display","inline-table");
       }
     })
     .fail(function(data) {
       ajaxResponseResult(data);
     })
     .always(function(myJsonResult) {
     });
 }else
 {
  insertRows();
 }
 }

 function checkIsEnabledBind(i)
 {
 if(stringToBoolean(arrAuthItem[getAuthShopCurrent()+getSyncFieldCurrent()+""][i]["IsFromItemHasShareTo"])) return false;
 if(stringToBoolean(arrAuthItem[getAuthShopCurrent()+getSyncFieldCurrent()+""][i]["IsToItemHasShareFrom"])) return false;
 if(stringToBoolean(arrAuthItem[getAuthShopCurrent()+getSyncFieldCurrent()+""][i]["IsToItemHasShareTo"])) return false;
 return true;
 }

 function setSyncValueToCom()
 {
 var numIidsSelf="";
 var numIidsAuth="";
 var isBind="";
    var isRadioUnChecked = false;

 $(".enableCheckbox:checked").each(function()
 {
  if(checkIsEnabledBind($(this).attr("index")))
  {
        var checkBoxIndex = $(this).attr("index");
        var radioIndex = 0;
        isRadioUnChecked = false;
        // 通过[0]判断radio是否存在
  if($('input:radio[name=radio'+checkBoxIndex+']')[0])
        {
          var isCheckedLabel = false;
          // 检查每个radio选项是否被选择
          $('input:radio[name=radio'+checkBoxIndex+']').each(function()
          {
            if($('input:radio[name=radio'+checkBoxIndex+']')[radioIndex].checked)
            {
              isCheckedLabel = true;
              // 这里是跳出each循环(里层)
              return false;
            }
            radioIndex++;
          });
          if(!isCheckedLabel)
            isRadioUnChecked = true;
          // 如果存在checkbox有选择,但是radio没选择,应该提醒
          // 然后就退出了,没有后续的提交
          if(isRadioUnChecked)
          {
            checkBoxIndex++;
            alert("第"+checkBoxIndex+"个宝贝有多个对应的授权宝贝,应该仔细查看并选择合适的宝贝同步!");
            // 这里跳出循环(外层)
            return false;
          }
        }

        var arrAuth = arrAuthItem[getAuthShopCurrent()+getSyncFieldCurrent()+""][checkBoxIndex]["ListItemFrom"]

        if(numIidsSelf=="")
  {
   numIidsSelf+=arrAuthItem[getAuthShopCurrent()+getSyncFieldCurrent()+""][checkBoxIndex]["NumIidTo"];
  }else
  {
   numIidsSelf+=","+arrAuthItem[getAuthShopCurrent()+getSyncFieldCurrent()+""][checkBoxIndex]["NumIidTo"];
  }

  if(numIidsAuth=="")
  {
   numIidsAuth+=arrAuth[radioIndex]["NumIid"];
  }else
  {
   numIidsAuth+=","+arrAuth[radioIndex]["NumIid"];
  }
  }
 });

 isBind=$("#isBind:checked").val()=="on"?"true":"false";

 $("#"+globalSyncVars.serverComClientId.HfNumIidsSelf).val(numIidsSelf);
 $("#"+globalSyncVars.serverComClientId.HfNumIidsAuth).val(numIidsAuth);
 $("#"+globalSyncVars.serverComClientId.HfIsBind).val(isBind);

    if(isRadioUnChecked) return -1;
    if(numIidsSelf=="") return 0;
    else return 1;
 }

 initTable=function()
 {
 refrash();
 isInited=true;
 }

 onSelectAllCheckbox=function()
 {
 if($("#selectAllCheckbox:checked").val()=="on")
 {
  selectAll(true);
 }else
 {
  selectAll(false);
 }
 }
 onPreview=function()
 {
 refrash();
 }

 onAldsItemSync=function(sender,jqgridObjRefresh)
 {
    var callbackCode = setSyncValueToCom();
 if(callbackCode == 0)
 {
  alert("没有可以同步设置的宝贝!");
  return;
 }else if(callbackCode == -1)
    {
      // 当存在没有选择的radio时
      return;
    }
 var urledit="./x.aspx?method=SaveSyncItem&rmd="+Math.random();
 $.post(urledit,$("#"+globalSyncVars.serverComClientId.form1).serialize())
 .done(function(myJsonResult) {
      var data = $.evalJSON(myJsonResult);
      ajaxResponseResult(data);

      if (data.IsSuccess)
      {
        showPrompt(data.PromptMsg);

        if(sender)
        {
         $(sender).dialog("close");
         $(sender).dialog("destroy");
        }
        if(jqgridObjRefresh)
        {
         $(jqgridObjRefresh).trigger("reloadGrid");
        }
      }
    })
    .fail(function(data) {
      ajaxResponseResult(data);
    })
    .always(function(myJsonResult) {
    });
 }
})();

示例二:有继承关系的js组件

(function(){
 //____________________________批量修改的基类_________________________________
 function BatchModify(){}
 //选择了什么id
 BatchModify.prototype.numIids=null;
 BatchModify.prototype.addis=null;
 BatchModify.prototype.oneIid=null;
 BatchModify.prototype.skuIds=null;
 BatchModify.prototype.selectedItemData=null;
 BatchModify.prototype.maxHeightVal=$(window).height()*0.9;

 // 完全克隆一个数组
 BatchModify.prototype.cloneArr=function(arr)
 {
 var arrNew = [];
 for(var i=0;i<arr.length;i++)
 {
  arrNew.push(arr[i]);
 }
 return arrNew;
 }

 // 通过jqGrid('getGridParam','selarrrow');取值是不可靠的,经常会变动
 // 在设置jqGrid('setSelection',bindedArr[i]);之后取出来的值经常会变化,要么长度变化,要么顺序变化
 BatchModify.prototype.cancelBindedItem=function()
 {
 var tempNumIids=jQuery("#listItemDefine").jqGrid('getGridParam','selarrrow');
 var tempNumIidsClone = this.cloneArr(tempNumIids);
 var isAlert=false;
 for(var i=0;i<bindedArr.length;i++)
 {
  for(var j=0;j<tempNumIidsClone.length;j++)
  {
  if(tempNumIidsClone[j]==bindedArr[i])
  {
   isAlert=true;
   jQuery("#listItemDefine").jqGrid('setSelection',bindedArr[i]);
   break;
  }
  }
 }
 if(isAlert) alert("已经绑定了数据来源的宝贝不能修改宝贝设置,如果需要修改请先点击宝贝最右栏的解绑按钮解绑!");
 }

 BatchModify.prototype.setNumIids=function()
 {
 this.numIids=jQuery("#listItemDefine").jqGrid('getGridParam','selarrrow');
 };
 //拼装addi的json串并赋值给addi
 BatchModify.prototype.setAddis=function()
 {
 var _addis="{rows:{";

   for(var i=0;i<this.numIids.length;i++)
   {
     _addis+='"'+this.numIids[i]+'":"';
     var tempVal=$("#addiTextId"+this.numIids[i]).val();
     var val=tempVal.replace(/\"/ig,"\'");
     _addis+=val;
     _addis+='"'

     if(i!=this.numIids.length-1)
     {
       _addis+=',';
     }
   }
   _addis+="}}";
   this.addis=_addis;
 };
 //(单个)修改页面传进来的一个id
 BatchModify.prototype.setOneIid=function()
 {
 this.oneIid=$("#"+itemEditVars.itemEditClientId.HfNumIid).val();
 };
 //sku的所有已选id(一个字符串)
 BatchModify.prototype.setSkuIds=function()
 {
 this.skuIds=jQuery("#listSkuDefine").jqGrid('getGridParam','selarrrow');
 };

 //设置numIids的值到服务器组件
 BatchModify.prototype.setNumIidsToCom=function()
 {
 $("#"+globalVars.serverComClientId.HfItemDefineIdsSelect).val(this.numIids);
 };
 //设置addis的值到服务器组件
 BatchModify.prototype.setAddisToCom=function()
 {
 $("#"+globalVars.serverComClientId.HfAddiStr).val(this.addis);
 };
 //检查是否有勾选宝贝
 BatchModify.prototype.checkIsSelected=function()
 {
   if (this.numIids == "") {
     alert("请选中要批量修改的行!");
     return false;
   }
   return true;
 };
 //批量生成描述
 BatchModify.prototype.batchGenerateDesc=function(alertResult)
 {
 this.setNumIidsToCom();
    var urledit = "x.aspx?method=BatchGenerateDesc&rdm=" + Math.random();
    if (alertResult)
      urledit += "&generateByManual=true";

    this.postData(urledit,alertResult);
 };
 //post数据
 BatchModify.prototype.postData=function(urledit,alertResult)
 {
 $.post( urledit, $("#"+globalVars.serverComClientId.formAldsItemDefine1).serialize())
    .done(function(myJsonResult) {
      var data = $.evalJSON(myJsonResult);
      ajaxResponseResult(data);

      if (data.IsSuccess) {
        if (!data.rows)
          showPrompt("宝贝描述生成修改成功!");
      }
      if(alertResult && data.ErrMsg && $.trim(data.ErrMsg) != "")
        alert("提醒:\n\n" + data.ErrMsg);
    })
    .fail(function(data) {
      ajaxResponseResult(data);
    })
    .always(function(myJsonResult) {
    });
 };

 BatchModify.prototype.removeDialog=function()
 {
 try{ $("#descTempDiv").remove(); } catch(e){}
 }

 function myInherits(Child,Parent)
 {
   function F(){}
   F.prototype=Parent.prototype;
   Child.prototype=new F();
   Child.prototype.constructor=Child;
 } 

 function createobject(proto)
 {
   function F(){}
   F.prototype=proto;
   return new F();
 }
 //_________________________批量修改(附言,确认收货后发消息,好评后发消息)类_________________________________
 function BatchMsgModify(title,tableId,paperId,fieldName,editUrl,containerDivStr)
 {
 BatchModify.call();
 this.title=title;
 this.tableId=tableId;
 this.paperId=paperId;
 this.fieldName=fieldName;
 this.editUrl=editUrl;
 this.containerDivStr=containerDivStr;
 }

 myInherits(BatchMsgModify,BatchModify);
 //弹窗
 BatchMsgModify.prototype.popUpDialog=function()
 {
 $(this.containerDivStr).dialog({
  title: this.title,
     closeText: '关闭',
     width: 980,
     maxHeight: $(window).height() * 0.98,
     minHeight: $(window).height() * 0.7,
     modal: true,
     show: { effect: "fade", duration: 300 },
     hide: { effect: "fade", duration: 300 },
     buttons: {
       确定: function() {
         currentInstance.confirmCallback(this);
       },
       关闭: function() {
         $(this).dialog("close");
       }
     }
 });
 };
 //创建表格
 BatchMsgModify.prototype.createTable=function()
 {
 $("#"+this.tableId).jqGrid({
     viewrecords: true, // show the current page, data rang and total records on the toolbar
     datatype: 'local',
     rowNum:100,
     rowList:[100],
     height: "auto",
     pager: "#"+this.paperId,
     colNames:['主图','宝贝','NumIid','Price','OuterId',this.title.indexOf("批量修改")>=0?this.title.substring(4):this.title],
     colModel:[
       {name:'PicUrl', index: 'PicUrl', width: 60, align: "center", sortable: false, formatter: imgFormatter, unformat:imgUnFormat},
       {name:'Title',index:'OuterId', width:430, sortable: true, formatter: itemDescFormatter, unformat:itemDescUnFormat},
       {name:'NumIid',index:'NumIid', width:100, hidden:true, key:true},
       {name:'Price',index:'Price', width:100, hidden:true},
       {name: 'OuterId', index: 'OuterId', width: 100, hidden: true },
       {name: this.fieldName, index: this.fieldName, width: 440, sortable: true, hidden: false, formatter:this.formatter}
     ]
   });
 };
 //把表格填充进数据
 BatchMsgModify.prototype.initTable=function()
 {
 var gridArrayData=[];
   for(var i=0;i<this.numIids.length;i++)
   {
     var curRowData=jQuery("#listItemDefine").jqGrid('getRowData',this.numIids[i]);

     var obj=new Object();
     obj["PicUrl"]=curRowData.PicUrl;
     obj["Title"]=curRowData.Title;
     obj["NumIid"]=curRowData.NumIid;
     obj["Price"]=curRowData.Price;
     obj["OuterId"]=curRowData.OuterId;
     obj[this.fieldName]=curRowData[this.fieldName];
     gridArrayData.push(obj);
   }
   $("#"+this.tableId).jqGrid('setGridParam',{data:gridArrayData});
   $("#"+this.tableId).trigger('reloadGrid');
 };
 //格式化字段
 BatchMsgModify.prototype.formatter=function(cellvalue,options,rowdata)
 {
 return "<TextArea id='addiTextId"+rowdata.NumIid+"' style='width:98%;' rows='4'>"+rowdata[currentInstance.fieldName]+"</TextArea>";
 };
 //重写post函数
 BatchMsgModify.prototype.postData=function(urledit,sender)
 {
 $.post( urledit, $("#"+globalVars.serverComClientId.formAldsItemDefine1).serialize())
   .done(function(myJsonResult)
   {
     var data = $.evalJSON(myJsonResult);
     ajaxResponseResult(data);
     if (data.IsSuccess) {
       if (!data.rows)
         showPrompt(currentInstance.title+"成功"+currentInstance.numIids.length+"个!");
       $("#listItemDefine").trigger('reloadGrid');
       setTimeout(function () { $(sender).dialog("close"); }, 0);
       setTimeout(function () { $(sender).dialog("destroy"); }, 1000);
     }
     if(data.ErrMsg && $.trim(data.ErrMsg) != "")
       alert(currentInstance.title+"出错:\n\n" + data.ErrMsg);
   })
   .fail(function(data) {
     ajaxResponseResult(data);
   })
   .always(function(myJsonResult) {
   });
 };

 //确认按钮的回调函数
 BatchMsgModify.prototype.confirmCallback=function(sender)
 {
   this.setAddis();
   this.setNumIidsToCom();
   this.setAddisToCom();
   this.postData(this.editUrl+"&rdm=" + Math.random(),sender);
 };

 //实例

 var batchAddi=null;
 var batchMsgTradeSuccess=null;
 var batchMsgRatedGood=null;
 var currentInstance=null;//指向当前对象,当this指向失效的时候可以使用这个

 openBatchMsgDialogType={batchAddi:0,batchMsgTradeSuccess:1,batchMsgRatedGood:2};
 openBatchMsgDialog=function(typeCode)
 {

 if(typeCode==openBatchMsgDialogType.batchAddi)
 {
  if (batchAddi==null)
  batchAddi=new BatchMsgModify("批量修改附言","tableEditContent","tablePaper","Additional","x.aspx?method=UpdateMsgAdditional","<div id='editBatchDiv'><table id='tableEditContent'></table><div id='tablePaper'></div></div>");
  currentInstance=batchAddi;
  batchAddi.cancelBindedItem();
  batchAddi.setNumIids();
  if(!batchAddi.checkIsSelected())
  return;
      batchAddi.popUpDialog();
      batchAddi.createTable();
      batchAddi.initTable();
 }else if (typeCode==openBatchMsgDialogType.batchMsgTradeSuccess)
 {
  if (batchMsgTradeSuccess==null)
  batchMsgTradeSuccess=new BatchMsgModify("批量修改确认收货后发消息","tableEditMsgTradeSuccessContent","tableMsgTradeSuccessPaper","MsgTradeSuccess","x.aspx?method=UpdateMsgTradeSuccess","<div id='editBatchDiv'><table id='tableEditMsgTradeSuccessContent'></table><div id='tableMsgTradeSuccessPaper'></div></div>");
  currentInstance=batchMsgTradeSuccess;
  batchMsgTradeSuccess.cancelBindedItem();
  batchMsgTradeSuccess.setNumIids();
  if(!batchMsgTradeSuccess.checkIsSelected())
  return;
      batchMsgTradeSuccess.popUpDialog();
      batchMsgTradeSuccess.createTable();
      batchMsgTradeSuccess.initTable();
 }else if (typeCode==openBatchMsgDialogType.batchMsgRatedGood)
 {
  if (batchMsgRatedGood==null)
  batchMsgRatedGood=new BatchMsgModify("批量修改好评后发消息","tableEditMsgRatedGoodContent","tableMsgRatedGoodPaper","MsgRatedGood","x.aspx?method=UpdateMsgRatedGood","<div id='editBatchDiv'><table id='tableEditMsgRatedGoodContent'></table><div id='tableMsgRatedGoodPaper'></div></div>");
  currentInstance=batchMsgRatedGood;
  batchMsgRatedGood.cancelBindedItem();
  batchMsgRatedGood.setNumIids();
  if(!batchMsgRatedGood.checkIsSelected())
  return;
      batchMsgRatedGood.popUpDialog();
      batchMsgRatedGood.createTable();
      batchMsgRatedGood.initTable();
 }
 }
 //_______________________________批量修改宝贝类(弹出单独页面,只要弹窗即可)_________________________________
 function BatchItemModify(){}

 myInherits(BatchItemModify,BatchModify);
 //重写
 BatchItemModify.prototype.popUpDialog=function()
 {
 var urledit = "./x.aspx?NumIids="+this.numIids+"&rdm="+Math.random();
    $.get(urledit, {}, function (data, textStatus, object) {
      var str = "<div id='editBatchDiv'>" + object.responseText + "</div>";
      $(str).dialog({
        dialogClass: "untitle",
        closeText: '关闭',
        width: 800,
        height: 400,
        maxHeight: $(window).height() * 0.9,
        modal: true,
        show: { effect: "fade", duration: 300 },
        hide: { effect: "fade", duration: 300 },
        buttons: {
          确定: function() {
            submitAldsItemEditBatch(this, $("#listItemDefine")); //在x.aspx定义
            currentInstance.batchGenerateDesc();
          },
          关闭: function() {
            $( this ).dialog( "close" );
          }
        }
      });
    });
 }

 //实例
 var batchItem=null;
 openBatchItemDialog=function()
 {
 if (batchItem==null)
  batchItem=new BatchItemModify();
 currentInstance=batchItem;
 batchItem.cancelBindedItem();
 batchItem.setNumIids();
 if(!batchItem.checkIsSelected())
  return;
 batchItem.popUpDialog();
 }
 //_______________________________批量生成宝贝描述__________________________________________
 function BatchDescModify(){}

 myInherits(BatchDescModify,BatchModify);

 BatchDescModify.prototype.generating=function()
 {
 if (!confirm("提醒。\n\n是否继续?"))
      return;
    this.batchGenerateDesc(true);
 };

 //实例
 var batchDesc=null;
 onBatchDesc=function()
 {
 if(batchDesc==null)
  batchDesc=new BatchDescModify();
 currentInstance=batchDesc;
 batchDesc.setNumIids();
 if(!batchDesc.checkIsSelected())
  return;
 batchDesc.generating();
 }
 //_____________________________________修改模板______________________________________________
 onDescMouldDialog=function()
 {
 var urledit = "./x.aspx?rdm="+Math.random();
    $.get(urledit,{},function(data,textStatus,object){
      var str="<div id='descTempDiv'>"+object.responseText+"</div>";
      $(str).dialog({
        title:'修改描述模板',
        closeText:'关闭',
        width:850,
        maxHeight:$(window).height() * 0.98,
        modal:true,
        show:{effect:"fade",duration:300},
        hide:{effect:"fade",duration:300},
        buttons:{
          确定:function()
          {
            onTempParaChangeHandler(this);
          },
          关闭:function()
          {
            $(this).dialog("close");
          }
        }
      });

    });
 }
 //___________________________________批量修改sku_______________________________________
 function BatchSkuModify(){}

 myInherits(BatchSkuModify,BatchModify);

 BatchSkuModify.prototype.popUpDialog=function()
 {
 var urledit = "./x.aspx?NumIids="+this.oneIid+"&SkuIds="+this.skuIds+"&IsSkuEditBatch=true&rdm="+Math.random();
    $.get(urledit, {}, function (data, textStatus, object) {
      var str = "<div id='descTempDiv'>" + object.responseText + "</div>";
      $(str).dialog({
        dialogClass: "untitle",
        closeText: '关闭',
        width: 800,
        height: 400,
        maxHeight: $(window).height() * 0.9,
        modal: true,
        show: { effect: "fade", duration: 300 },
        hide: { effect: "fade", duration: 300 },
        buttons: {
          确定: function() {
            submitAldsItemEditBatch(this, $("#listSkuDefine")); //在x.aspx定义
          },
          关闭: function() {
            $( this ).dialog( "close" );
          }
        }
      });
    });
 };

 BatchSkuModify.prototype.checkIsSelected=function()
 {
   if (this.skuIds == "") {
     alert("请选中要批量修改的SKU!");
     return false;
   }
   return true;
 };
 //实例
 var batchSku=null;

 openBatchSkuDialog=function()
 {
 if(batchSku==null)
  batchSku=new BatchSkuModify();
 currentInstance=batchSku;
 batchSku.setOneIid();
 batchSku.setSkuIds();
 batchSku.removeDialog();
 if(!batchSku.checkIsSelected())
  return;
 batchSku.popUpDialog();
 }
 //_______________________________批量修改SKU附言__________________________________________________

 function BatchSkuMsgModify(title,tableId,paperId,fieldName,editUrl,containerDivStr)
 {
 BatchModify.call();
 this.title=title;
 this.tableId=tableId;
 this.paperId=paperId;
 this.fieldName=fieldName;
 this.editUrl=editUrl;
 this.containerDivStr=containerDivStr;
 }
 myInherits(BatchSkuMsgModify,BatchModify);

 BatchSkuMsgModify.prototype.popUpDialog=function()
 {
 $(this.containerDivStr).dialog({
  title: this.title,
     closeText: '关闭',
     width: 980,
     maxHeight: this.maxHeightVal,
     // height: this.maxHeightVal>750 ? 750 : this.maxHeightVal,
     modal: true,
     show: { effect: "fade", duration: 300 },
     hide: { effect: "fade", duration: 300 },
     buttons: {
       确定: function() {
         currentInstance.confirmCallback(this);
       },
       关闭: function() {
         $(this).dialog("close");
       }
     }
 });
 };
 //重写-创建表格
 BatchSkuMsgModify.prototype.createTable=function()
 {
 $("#"+this.tableId).jqGrid({
     viewrecords: true, // show the current page, data rang and total records on the toolbar
     datatype: 'local',
     rowNum:100,
     rowList:[100],
     height: "auto",
     pager: "#"+this.paperId,
     colNames:['SkuId','属性名',this.title.indexOf("批量修改")>=0?this.title.substring(4):this.title],
     colModel:[
     {name:'SkuId',index:'SkuId', width:400, hidden:true, key:true},
     {name:'PropertiesName',index:'PropertiesName', width:400,sortable:false, editable: false, hiden:false},
     {name: this.fieldName, index: this.fieldName, width: 440, sortable: true, hidden: false, formatter:this.formatter}
     ]
   });
 };
 //把表格填充进数据
 BatchSkuMsgModify.prototype.initTable=function()
 {
 var gridArrayData=[];
   for(var i=0;i<this.skuIds.length;i++)
   {
     var curRowData=jQuery("#listSkuDefine").jqGrid('getRowData',this.skuIds[i]);

     var obj=new Object();
     obj["SkuId"]=curRowData.SkuId;
     obj["PropertiesName"]=curRowData.PropertiesName;
     obj[this.fieldName]=curRowData[this.fieldName];
     gridArrayData.push(obj);
   }

   $("#"+this.tableId).jqGrid('setGridParam',{data:gridArrayData});
   $("#"+this.tableId).trigger('reloadGrid');
 };
 //重写-格式化字段
 BatchSkuMsgModify.prototype.formatter=function(cellvalue,options,rowdata)
 {
 return "<TextArea id='addiTextId"+rowdata.SkuId+"' style='width:98%;' rows='4'>"+rowdata[currentInstance.fieldName]+"</TextArea>";
 };
 //重写post函数
 BatchSkuMsgModify.prototype.postData=function(urledit,sender)
 {
 $.post( urledit, $("#"+itemEditVars.itemEditClientId.formAldsItemEdit1).serialize())
   .done(function(myJsonResult)
   {
     var data = $.evalJSON(myJsonResult);
     ajaxResponseResult(data);
     if (data.IsSuccess) {
       if (!data.rows)
         showPrompt(currentInstance.title+"成功"+currentInstance.skuIds.length+"个!");
       $("#listSkuDefine").trigger('reloadGrid');
       setTimeout(function () { $(sender).dialog("close"); }, 0);
       setTimeout(function () { $(sender).dialog("destroy"); }, 1000);
     }
     if(data.ErrMsg && $.trim(data.ErrMsg) != "")
       alert(currentInstance.title+"出错:\n\n" + data.ErrMsg);
   })
   .fail(function(data) {
     ajaxResponseResult(data);
   })
   .always(function(myJsonResult) {
   });
 };
 //重写-拼装json
 BatchSkuMsgModify.prototype.setAddis=function()
 {
 var _addis="{rows:{";

   for(var i=0;i<this.skuIds.length;i++)
   {
     _addis+='"'+this.skuIds[i]+'":"';
     var tempVal=$("#addiTextId"+this.skuIds[i]).val();
     var val=tempVal.replace(/\"/ig,"\'");
     _addis+=val;
     _addis+='"'

     if(i!=this.skuIds.length-1)
     {
       _addis+=',';
     }
   }
   _addis+="}}";
   this.addis=_addis;
 };
 //重写-设置numIids到组件
 BatchSkuMsgModify.prototype.setNumIidsToCom=function()
 {
 $("#"+itemEditVars.itemEditClientId.HfNumIid).val(this.oneIid);
 };

 //新增-设置skuids到组件
 BatchSkuMsgModify.prototype.setSkuIdsToCom=function()
 {
 $("#"+itemEditVars.itemEditClientId.HfSkuIds).val(this.skuIds);
 };
 //重写
 BatchSkuMsgModify.prototype.setAddisToCom=function()
 {
 $("#"+itemEditVars.itemEditClientId.HfSkuAddiStr).val(this.addis);
 };

 //确认按钮的回调函数
 BatchSkuMsgModify.prototype.confirmCallback=function(sender)
 {
   this.setAddis();
   this.setNumIidsToCom();
   this.setSkuIdsToCom();
   this.setAddisToCom();
   currentInstance.postData(this.editUrl+"&rdm=" + Math.random(),sender);
 };
 //
 BatchSkuMsgModify.prototype.checkIsSelected=function()
 {
   if (this.skuIds == "") {
     alert("请选中要批量修改附言的SKU!");
     return false;
   }
   return true;
 };

 //实例
 var batchSkuAddi=null;
 openBatchSkuMsgDialogType={batchSkuAddi:0};
 openBatchSkuMsgDialog=function(typeCode)
 {
 if (typeCode==openBatchSkuMsgDialogType.batchSkuAddi)
 {
  if (batchSkuAddi==null)
  batchSkuAddi=new BatchSkuMsgModify("批量修改SKU附言","tableEditContent","tablePaper","Additional","x.aspx?method=UpdateMsgAdditional","<div id='descTempDiv'><table id='tableEditContent'></table><div id='tablePaper'></div></div>");
  currentInstance=batchSkuAddi;
  batchSkuAddi.removeDialog();
  batchSkuAddi.setOneIid();
  batchSkuAddi.setSkuIds();
  if(!batchSkuAddi.checkIsSelected())
  return;
      batchSkuAddi.popUpDialog();
      batchSkuAddi.createTable();
      batchSkuAddi.initTable();
 }
 }
 //_______________________________生成描述_________________________________________________
 var descBatchModify=null;

 batchGenerateDesc=function(descNumIds,alertResult)
 {
 if(descBatchModify==null)
  descBatchModify=new BatchModify();
 descBatchModify.numIids=descNumIds;
 descBatchModify.setNumIidsToCom();
 descBatchModify.batchGenerateDesc(alertResult);
 }

 //_______________________________同步类(弹出单独页面,只要弹窗即可)_________________________________
 function SyncModify(){}

 myInherits(SyncModify,BatchModify);
 //重写
 SyncModify.prototype.popUpDialog=function()
 {
 var urledit="./x.aspx?rdm="+Math.random();

 $.post(urledit,{numIids:this.numIids.toString()},function(data,textStatus,object){
  var str = "<div id='descTempDiv'>" + object.responseText + "</div>";
      $(str).dialog({
       title:"同步设置",
        closeText: '关闭',
        width: 1150,
        height: 800,
        maxHeight: $(window).height() * 0.9,
        modal: true,
        show: { effect: "fade", duration: 300 },
        hide: { effect: "fade", duration: 300 },
        buttons: {
          同步: function() {
            onAldsItemSync(this, $("#listItemDefine")); //在x.aspx定义
          },
          取消: function() {
            $( this ).dialog( "close" );
          }
        }
      });
 });
 }

 var syncModify=null;
 openSyncDialog=function()
 {
 if(syncModify==null)
  syncModify=new SyncModify();
 currentInstance=syncModify;
 syncModify.setNumIids();
 if(!syncModify.checkIsSelected())
  return;
 syncModify.removeDialog();
 syncModify.popUpDialog();
 }
 //____________________________同步SKU设置(弹出单独页面,只需弹窗)___________________________________
 function SyncSkuModify(){}
 myInherits(SyncSkuModify,BatchModify);

 SyncSkuModify.prototype.popUpDialog=function()
 {
 var urledit="./x.aspx?rdm="+Math.random();

 $.post(urledit,{numIid:currentInstance.oneIid.toString(),skuIds:currentInstance.skuIds.toString()},function(data,textStatus,object){
  var str = "<div id='descTempDiv'>" + object.responseText + "</div>";
      $(str).dialog({
       title:"同步SKU设置",
        closeText: '关闭',
        width: 1150,
        height: 800,
        maxHeight: $(window).height() * 0.9,
        modal: true,
        show: { effect: "fade", duration: 300 },
        hide: { effect: "fade", duration: 300 },
        buttons: {
          同步: function() {
            onAldsSkuSync(this, $("#listSkuDefine")); //在x.aspx定义
          },
          取消: function() {
            $( this ).dialog( "close" );
          }
        }
      });
 });
 }

 SyncSkuModify.prototype.checkIsSelected=function()
 {
   if (this.skuIds == "") {
     alert("请选中要同步设置的SKU!");
     return false;
   }
   return true;
 };

 var syncSkuModify=null;
 openSkuSyncDialog=function()
 {
 if($("#"+itemEditVars.itemEditClientId.HfNumIidFrom).val()=="none")
 {
  alert("没有找到已经绑定的宝贝!要同步SKU设置,需要先绑定对应的宝贝,才能同步宝贝下面的SKU!");
  return;
 }
 if(syncSkuModify==null)
  syncSkuModify=new SyncSkuModify();
 currentInstance=syncSkuModify;
 syncSkuModify.setOneIid();
 syncSkuModify.setSkuIds();
 if (!syncSkuModify.checkIsSelected())
  return;
 syncSkuModify.removeDialog();
 syncSkuModify.popUpDialog();
 }
 //__________________________item批量(及单独)解除绑定_________________________________
 function BatchDisBindingItem(){}
 myInherits(BatchDisBindingItem,BatchModify);

 // 对非绑定item取消勾选,是为了下一步批量解除绑定
 BatchDisBindingItem.prototype.cancelFreeItem=function()
 {
 var isAlert = false;
 var isBinded = false;
 var tempNumIids = jQuery("#listItemDefine").jqGrid('getGridParam', 'selarrrow');
 var tempNumIidsClone = this.cloneArr(tempNumIids);
 for (var i = 0; i < tempNumIidsClone.length; i++) {
   var numIidTmp = tempNumIidsClone[i];
   var curRowData = jQuery("#listItemDefine").jqGrid('getRowData', numIidTmp);
   if (curRowData.NumIidFrom == "none") {
     isAlert = true;
     jQuery("#listItemDefine").jqGrid('setSelection', numIidTmp);
   }
 }
 if (isAlert)
 {
   alert("未绑定的宝贝不能作解绑的动作!");
   // return true 表示已经alert了
   return true;
 }
 return false;
 }
 BatchDisBindingItem.prototype.popUpDialog=function()
 {
 var showStr='<div id="descTempDiv"><span style="color:red;">注意:您正在批量解除绑定,如果您解除了绑定,今后数据源宝贝设置有更新您的宝贝设置将不会同步更新!</span></div>';

    $(showStr).dialog({
      title: "解除绑定",
      closeText: '关闭',
      width: 600,
      height:300,
      maxHeight: $(window).height() * 0.98,
      minHeight: $(window).height() * 0.7,
      modal: true,
      show: { effect: "fade", duration: 300 },
      hide: { effect: "fade", duration: 300 },
      buttons: {
        解绑: function() {
          disBindingItem(currentInstance.numIids,this);
        },
        关闭: function() {
          $(this).dialog("close");
        }
      }
    });
 }

 var batchDisBindItemInstance = null;
 batchDisBindingItem=function()
 {
 var isAlerted = false;
 if(batchDisBindItemInstance==null)
  batchDisBindItemInstance=new BatchDisBindingItem();
 currentInstance=batchDisBindItemInstance;
 if(batchDisBindItemInstance.cancelFreeItem())
  isAlerted = true;
 batchDisBindItemInstance.setNumIids();

 if(isAlerted)
 {
  if(currentInstance.numIids=="") return;
 }

 if(!batchDisBindItemInstance.checkIsSelected())
  return;
 batchDisBindItemInstance.removeDialog();
 batchDisBindItemInstance.popUpDialog();
 }
 disBindingItem=function(myNumIids,sender)
  {
    var urledit = "./x.aspx?method=DisBinding&NumIids="+myNumIids+"&rdm="+Math.random();
    $.get(urledit, {}, function (dataString, status, object) {
      var data = $.evalJSON(dataString);
      ajaxResponseResult(data);
      if(data.IsSuccess==true)
      {
        $(sender).dialog("close");
        $("#listItemDefine").trigger("reloadGrid");
      }
    });
  }
  //____________________________sku批量及单独解除绑定____________________________________________
  function BatchDisBindingSku(){}
  myInherits(BatchDisBindingSku,BatchSkuModify);

  BatchDisBindingSku.prototype.cancelFreeItem=function()
  {
   var tempNumIids = jQuery("#listSkuDefine").jqGrid('getGridParam','selarrrow');
 var tempNumIidsClone = this.cloneArr(tempNumIids);
 var isAlert=false;
 var isBinded = false;
 for(var i=0;i<tempNumIidsClone.length;i++)
 {
  isBinded = false;
  for(var j=0;j<bindedSkuArr.length;j++)
  {
  if(tempNumIidsClone[i]==bindedSkuArr[j])
  {
   isBinded = true;
   break;
  }
  }
  if(!isBinded)
  {
  isAlert = true;
  jQuery("#listSkuDefine").jqGrid('setSelection',tempNumIidsClone[i]);
  }
 }

 if(isAlert)
 {
  alert("未绑定的SKU不能作解绑的动作!");
  // 返回true表示已经弹出alert了
  return true;
 }
 return false;
  }

  BatchDisBindingSku.prototype.popUpDialog=function()
 {
 var showStr='<div id="descTempDiv"><span style="color:red;">注意:您正在批量解除SKU绑定,如果您解除了绑定,今后数据源宝贝设置有更新您的宝贝设置将不会同步更新!</span></div>';

    $(showStr).dialog({
      title: "解除绑定",
      closeText: '关闭',
      width: 600,
      height:300,
      maxHeight: $(window).height() * 0.98,
      minHeight: $(window).height() * 0.7,
      modal: true,
      show: { effect: "fade", duration: 300 },
      hide: { effect: "fade", duration: 300 },
      buttons: {
        解绑: function() {
          disBindingSku(currentInstance.oneIid,currentInstance.skuIds,this);
        },
        关闭: function() {
          $(this).dialog("close");
        }
      }
    });
 }

 var batchDisBindSkuInstance = null;
 // 批量
 batchDisBindingSku=function()
 {
 var isAlerted = false;
 if(batchDisBindSkuInstance==null)
  batchDisBindSkuInstance=new BatchDisBindingSku();
 currentInstance=batchDisBindSkuInstance;
 if(batchDisBindSkuInstance.cancelFreeItem())
  isAlerted = true;
 batchDisBindSkuInstance.setOneIid();
 batchDisBindSkuInstance.setSkuIds();

 // 如果已经弹过一次了,那再次判断是否没有勾选的时候,就不要再弹了
 if(isAlerted)
 {
  if(currentInstance.skuIds == "") return;
 }

 if(!batchDisBindSkuInstance.checkIsSelected())
  return;
 batchDisBindSkuInstance.removeDialog();
 batchDisBindSkuInstance.popUpDialog();
 }
  // 单独
  disBindingSku=function(numIid, skuIds, sender) {
    var urledit = "./x.aspx?method=DisBinding&NumIid=" + numIid + "&SkuIds="+skuIds+"&rdm=" + Math.random();
    $.get(urledit, {}, function (dataString, status, object) {
      var data = $.evalJSON(dataString);
      ajaxResponseResult(data);
      if (data.IsSuccess == true) {
        $(sender).dialog("close");
        $("#listSkuDefine").trigger("reloadGrid");
      }
    });
  }

})();

以上这篇利用js的闭包原理做对象封装及调用方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • JS闭包的几种常见形式实例详解

    作用域链: //作用域链 var a = 1; function test() { var b =2; return a; } alert(test());//弹出1: alert(b);//不能获取b //scope chain var a = 1; function test() { var b = 2; function test1() { var c = 3; alert(a); alert(b); alert(c); } test1(); } test();//弹出1,弹出2,弹出3:

  • 深入理解javascript函数参数与闭包

    最近在学习javascript的函数,函数是javascript的一等对象,想要学好javascript,就必须深刻理解函数.本人把学习的过程整理成文章,一是为了加深自己函数的理解,二是给读者提供学习的途径,避免走弯路.内容有些多,但都是笔者对于函数的总结. 1.函数参数 1.1:参数是什么 1.2:参数的省略 1.3:参数默认值 1.4:参数传递方式 1.5:同名参数 1.6:arguments对象 2.闭包 2.1:闭包定义 2.2:立即调用的函数表达式(IIFE, Immediately

  • js闭包用法实例详解

    本文实例讲述了js闭包用法.分享给大家供大家参考,具体如下: 引言 在公司中需要写一个js脚本来进行网站的统计,实现类似百度统计或者站长统计的功能,在实现的过程中自己感觉写的代码还是可以的,因为之前的js代码都是这些写,但是在组长代码走查的时候却非常的不满意,因为我们在js中写的方法都是全局的方法,因为我们写的东西需要嵌入到别人的界面中,所以这些全局的东西很可能会和别人的东西重名从而引发错误,所以说组长就给我留下一句话:用js闭包包起来. 变量作用域 我们都非常的熟悉变量的作用域就分为:全局变量

  • JS 循环li添加点击事件 (闭包的应用)

    废话不多说了,直接给大家贴代码了,具体代码如下所述: var aLi = document.querySelectorAll('.article-tab li'); for (var i = 0; i <= aLi.length; i++) { (function(){ var p = i aLi[i].onclick = function() { alert(p); } })(); } 以上所述是小编给大家介绍的JS 循环li添加点击事件 (闭包的应用),希望对大家有所帮助,如果大家有任何疑问

  • 利用js的闭包原理做对象封装及调用方法

    创建一个js文件,名为testClosure.js: (function () { function a() { alert('i am a'); } outFunc = function () { a(); } })(); 这里不论写多少个function,a b c d ...外面都调用不到,包括这里面var定义的变量也都调用不到,那么你在里面尽情的写,就不用担心这些函数名变量名跟外界冲突: 只需要暴露一个outFunc这个函数供外界调用.这个函数呢没有用var定义,就变成一个全局变量,外界

  • 解决ajax不能访问本地文件问题(利用js跨域原理)

    博主自己在开发一个无后台,只有前台的查询系统时,遇到一个困难,如何利用Ajax读取自己的本地json文件,百度.谷歌了下,发现大部分文章都是在说修改浏览器参数,但是自己想想,用户在使用时,还要修改浏览器的参数,这样显然降低了用户体验.自己琢磨了一段时间,发现可以利用js跨域原理来解决这个瓶颈.将之前要读取的json文件,变为js对象文件,这样就可以读取这个文件,然后写一个函数来对这个js对象进行解析. 首先说明下js跨域原理和jsonp这个技术(如果说的不详细,可自行百度.谷歌) src可以跨域

  • 利用JS判断字符串是否含有数字与特殊字符的方法小结

    前言 本文主要介绍的是利用JS判断字符串是否含有数字与特殊字符的方法,文中有几种不同的方法,包括普通的JS验证法.正则表达式法,另外还有判断是否为浮点数的js函数,在最后还将简要介绍下isNAN函数的使用方法和例子,来一起学习学习吧. 一.正则表达式方法判断是否为数字,包括判断正整数: function checkRate(input) { var re = /^[0-9]+.?[0-9]*$/; //判断字符串是否为数字,//若判断正整数,则后边是:/^[1-9]+[0-9]*]*$/ if

  • js中比较两个对象是否相同的方法示例

    本文实例讲述了js中比较两个对象是否相同的方法.分享给大家供大家参考,具体如下: js中,很轻易就可以比较2个普通字符串/数字是否相同,但是,如何比较2个对象是否相同呢? 在此我便给出较为简单的方法,如下: //比较2个对象是否相同 function isObjEqual(o1,o2){ var props1 = Object.getOwnPropertyNames(o1); var props2 = Object.getOwnPropertyNames(o2); if (props1.leng

  • 易语言中Com对象的简单调用方法

    在说明com对象在易语言中的使用之前,让我们先来了解一下几个问题 什么是com? com全称是组件对象模型(compoment object model),他是一组规范,是MicroSoft创建的一组二进制和网络标准,用于解决两个组件之间的通信. 什么是com对象 com是面向对象的软件模型,com对象的概念有点类似于C++中对象的概念.在com规范中,没有com对象的严格定义,com组件提供给客户的是以对象形式封装起来的实体,客户与组件交互的实体是com对象. com对象有自己的属性和方法,但

  • WebService 的简单封装接口调用方法

    此方法完成了简单WebService 的简单调用封装,实现了简单Webservice简单调用的统一操作,避免了每增加一个操作都必须增加一个接口方法 的囧状! /// <summary> /// 封装同一的接口调用方法 /// </summary> /// <param name="_strSql">传入的简单sql</param> /// <param name="_strConnNmae">连接数据库字符

  • .NET中利用js让子窗体向父页面传值的实现方法

    子页面C#后台代码: 复制代码 代码如下: /// <summary>        /// 将设置好的值赋给父页面        /// </summary>        /// <param name="count">需要传递的值</param>        void SetValueToParentPage(int count, string strPersons)       {           StringBuilder

  • 利用JS解决ie6不支持max-width,max-height问题的方法

    今天遇到一个关于用js解决ie6不支持支持max-width,max-height的问题,刚开始用jQuery方法来实现,不过一直获取不到css里面的值,如 复制代码 代码如下: if($.browser.msie && $.browser.version == 6.0)  {    var maxWidth = parseInt($('.viewBigPic img').css('max-width'));    $('.viewBigPic img').each(function(){

  • JavaScript Window窗口对象属性和使用方法

    一.Window对象概述 Window对象可以用来打开浏览器,调整浏览器的位置.大小等等功能. Window对象可以处理框架和框架之间的关系,通过这种关系在一个框架中处理另一个框架中的文档.他也是所有对象的顶级对象,通过Window对象的子对象进行操作,可以实现更多的效果. 1.Window对象属性 每个对象都有自己的属性,顶级对象Window是所有其他子对象的父对象,它可以出现在每个页面上,并且可以咋单个JS应用程序中被多次使用. 下表列出了一些Window对象常用属性: 属性 说明 docu

  • 详解JS对象封装的常用方式

    JS是一门面向对象语言,其对象是用prototype属性来模拟的,下面,来看看如何封装JS对象. 常规封装 function Person (name,age,sex){ this.name = name; this.age = age; this.sex = sex; } Pserson.prototype = { constructor:Person, sayHello:function(){ console.log('hello'); } } 这种方式是比较常见的方式,比较直观,但是Per

随机推荐