js面向對象的寫法
1、在html中引入該js文件,使用時:html
<script> var BuyBw8Product = new buyBw8Product(); </script>
2、通常寫一個較大的模塊的js代碼時,採用這種方法寫js函數
新建一個js,內容結構以下:this
/** * create by wkk * 描述:*** */ !function(){ function b(){ var that = this; //當前是否到期集合 this.moduleIsExpired = { ticketIsExpired : $("#ticketIsExpired"), ccIsExpired : $("#ccIsExpired"), imIsExpired : $("#imIsExpired") }; //工單購買坐席數的change事件 $("#ticketSeatNum").on('change', (function(){ var ticketSeatNum = $(this).val() ? $(this).val() : 0; if(parseInt(ticketSeatNum) <= 0){ alert('請填寫正確的工單購買坐席數'); that.disableBuyButton(); // 清空工單的金額,新計算餘額 that.emptyMoney('ticket'); return false; } //購買工單週期 var ticketSeatYear = parseInt($(that.SeatYearSelect.ticketSeatYear).val()); //不存在週期,表示不過時而且原有坐席數不爲0 if($("#ticketSeatYear").length <= 0){ //計算新的週期 var ticketCurExpireTime = $(that.allCurExpireTime.ticketCurExpireTime).text(); //從今天到到期日期的天數差值 var todayDate = that.getTodayDate(); var expireTimeDays = that.DateDiff(todayDate, ticketCurExpireTime); var ticketSeatYear = (parseInt(expireTimeDays)/365).toFixed(8); } if(ticketSeatYear > 0){ //計算工單的金額 var ticketPrice = $(that.productPrice.ticketPrice).text(); //四捨五入->向下取整 var ticketTotalAmount = Math.floor(that.calcAmount(ticketSeatNum, ticketPrice, ticketSeatYear)); //顯示模塊金額和總金額以及折扣信息 that.showModuleTotalAmountAndTotalMoneyAndDiscount('ticket', ticketTotalAmount, ticketSeatNum, ticketSeatYear); } })); /** * 比較兩個日期的大小,返回值比較大的日期 * @param date1 * @param date2 * @returns date */ this.tab = function (date1,date2){ var oDate1 = new Date(date1); var oDate2 = new Date(date2); if(oDate1.getTime() >= oDate2.getTime()){ return date1; } else { return date2; } } /** * 返回今天的日期 格式:2018-08-08 */ this.getTodayDate = function(){ var myDate = new Date; var year = myDate.getFullYear();//獲取當前年 var month = myDate.getMonth()+1;//獲取當前月 var date = myDate.getDate();//獲取當前日 return year+'-'+month+'-'+date; } /** * 計算天數差的函數,通用 * @param sDate1 * @param sDate2 * @returns {Number} */ this.DateDiff = function(sDate1, sDate2){ //sDate1和sDate2是2006-12-18格式 var aDate, oDate1, oDate2, iDays aDate = sDate1.split("-") oDate1 = new Date(aDate[1] + '-' + aDate[2] + '-' + aDate[0]) //轉換爲12-18-2006格式 aDate = sDate2.split("-") oDate2 = new Date(aDate[1] + '-' + aDate[2] + '-' + aDate[0]) iDays = parseInt(Math.abs(oDate1 - oDate2) / 1000 / 60 / 60 /24) //把相差的毫秒數轉換爲天數 return iDays } } window.buyBw8Product = b; }();