本文實例講述了JavaScript構建自己的對象。分享給大家供大家參考,具體如下:
<script type='text/javascript'>//構建一個CustomerBooking類//構造函數function CustomerBooking(bookingId,customerName,film,showDate){ this.bookingId = bookingId; this.customerName = customerName; this.film = film; this.showDate =showDate;}//getBookingId方法,有點奇特CustomerBooking.prototype.getBookingId = function(){ return this.bookingId;}//setBookingId方法CustomerBooking.prototype.setBookingId = function(bookingId){ this.bookingId = bookingId;}CustomerBooking.prototype.getCustomerName = function(){ return this.customerName;}CustomerBooking.prototype.setCustomerName = function(customerName){ this.customerName = customerName;}CustomerBooking.prototype.getFilm = function(){ return this.film;}CustomerBooking.prototype.setFilm = function(film){ this.film = film;}CustomerBooking.prototype.getShowDate = function(){ return this.showDate;}CustomerBooking.prototype.setShowDate = function(showDate){ this.showDate = showDate;}//構建一個cineme類,屬性為數組,可以保存預定信息function cinema(){ this.bookings = new Array();}//addBooking方法cinema.prototype.addBooking = function(bookingId,customerName,film,showDate){ this.bookings[bookingId] = new CustomerBooking(bookingId,customerName,film,showDate);}//getBookingsTable方法cinema.prototype.getBookingsTable = function(){ var booking; var bookingsTableHTML="<table border=1>"; for(booking in this.bookings){ bookingsTableHTML +="<tr><td>"; bookingsTableHTML +=this.bookings[booking].getBookingId(); bookingsTableHTML +="</td>"; bookingsTableHTML +="<td>"; bookingsTableHTML +=this.bookings[booking].getCustomerName(); bookingsTableHTML +="</td>"; bookingsTableHTML +="<td>"; bookingsTableHTML +=this.bookings[booking].getFilm(); bookingsTableHTML +="</td>"; bookingsTableHTML +="<td>"; bookingsTableHTML +=this.bookings[booking].getShowDate(); bookingsTableHTML +="</td></tr>"; } bookingsTableHTML +="</table>"; return bookingsTableHTML;}//新建cinema對象就可以了,這里會通過addBooking自動生成customerBooking對象,保存到cinema對象bookingFilm的屬性當中,然后調用getBookingsTable方法來獲取數據信息var bookingFilm = new cinema();bookingFilm.addBooking(123,"Jack","Love Java","1 May 2012");bookingFilm.addBooking(123,"Jack","Love Java","1 May 2012");bookingFilm.addBooking(122,"Jack","Love Java","1 May 2012");bookingFilm.addBooking(121,"Jack","Love Java","1 May 2012");bookingFilm.addBooking(120,"Jack","Love Java","1 May 2012");bookingFilm.addBooking(119,"Jack","Love Java","1 May 2012");document.write(bookingFilm.getBookingsTable());</script>
更多關于JavaScript相關內容可查看本站專題:《javascript面向對象入門教程》、《JavaScript中json操作技巧總結》、《JavaScript切換特效與技巧總結》、《JavaScript查找算法技巧總結》、《JavaScript錯誤與調試技巧總結》、《JavaScript數據結構與算法技巧總結》、《JavaScript遍歷算法與技巧總結》及《JavaScript數學運算用法總結》
希望本文所述對大家JavaScript程序設計有所幫助。
新聞熱點
疑難解答