2013年4月27日 星期六

[JS]物件繼承範例

/*
 * 實作一個銀行帳戶跟存款帳戶,讓存款帳戶去繼承銀行帳戶
 * 並實作存款跟提款的方法
 * 
 *
 *
 * Account物件裡面有兩個屬性,三個方法
 * 屬性:帳戶、餘額
 * 方法:存款、提款、顯示帳戶資訊
 *
 *
 *
 */
 function Account(a_number){
  this.a_number = a_number;
  this.a_balance = 0;
  
  this.getBalance = function(){
   return this.a_balance;
  }
  this.deposit = function(amount){
   this.a_balance = this.a_balance + amount;
   return document.write('您在帳戶中存入 ' + this.a_balance + ' 元' + '

'); }; this.withdraw = function(amount){ document.write('您準備提領 ' + amount + ' 元,系統正準備驗証餘額...' + '

'); if(this.a_balance >= amount){ this.a_balance = this.a_balance - amount; return document.write('恭喜您提領成功! 您帳戶餘額: ' + this.a_balance + ' 元' + '

'); } else return document.write('餘額不足,提款失敗! 請重新輸入您的提款金額

'); }; this.show = function(){ document.write('銀行帳戶: ' + this.a_number + '

'); document.write('帳戶金額: ' + this.a_balance + ' 元

'); }; this.process = function(){ return (this.a_balance + (this.a_balance * this.interestRate)); } } //在下一行是讓SavingAccount去繼承Account,可以使用Account的屬性與方法 SavingAccount.prototype = new Account(); /* * * SavingAccount物件裡有一個屬性,四個方法 * 屬性:利率 * 方法:設定利率、取得利率、處理存款利息、顯示帳戶資訊 * */ function SavingAccount(s_number){ SavingAccount.prototype.a_number = s_number; this.interestRate = 0; this.setInterestRate = function(interestRate){ this.interestRate = interestRate; }; this.getInterestRate = function(){ return document.write('存款利率: ' + this.interestRate + ' %

'); }; SavingAccount.prototype.show = function(){ document.write('銀行帳戶: ' + this.a_number + '

'); document.write('帳戶金額: ' + this.a_balance + ' 元

'); document.write('存款利率: ' + this.interestRate + ' %

'); document.write('本金 + 存款利率: ' + this.process() + ' 元

'); }; } var aa = new SavingAccount(101); aa.setInterestRate(0.02); aa.deposit(500); aa.show(); aa.withdraw(700); aa.withdraw(200); aa.deposit(513); aa.show(); aa.deposit(694); aa.show();

顯示如下:



沒有留言:

張貼留言