HTML.CSS.JS/JS
[JS] class 예제 : 은행 (입금, 출금, 이체)
congs
2023. 4. 18. 16:43
1. let으로 하나씩 만들어 사용하는 경우
<!-- 하나씩 넣는 경우 -->
<script>
let myAccount = {
//이름
name: 'hong',
//잔액
balance: 0,
//입금
deposit: function(amount){
this.balance += amount;
},
//출금
withdraw: function(amount){
this.balance -= amount;
},
//이체
transfer: function(amount, otherAccount){
this.balance -= amount;
otherAccount.balance += amount;
}
};
let yourAccount = {
//이름
name: 'kim',
//잔액
balance: 100,
//입금
deposit: function(amount){
this.balance += amount;
},
//출금
withdraw: function(amount){
this.balance -= amount;
},
//이체
transfer: function(amount, otherAccount){
this.balance -= amount;
otherAccount.balance += amount;
}
};
//현재 내 계좌 출력 (이름:잔액)
console.log(myAccount.name, ':', myAccount.balance); // hong:0
//내 계좌에 입금
myAccount.deposit(500); // hong:500
console.log(myAccount.name, ':', myAccount.balance);
//내 계좌 출금
myAccount.withdraw(100); // hong:400
console.log(myAccount.name, ':', myAccount.balance);
//내 계좌에서 송금
myAccount.transfer(200,yourAccount); // hong:200 kim:300
console.log(myAccount.name, ':', myAccount.balance);
console.log(yourAccount.name, ':', yourAccount.balance);
</script>
2. class로 생성자를 만들어 놓고, 객체를 생성해 사용하는 경우
<!-- class로 지정해 생성자로 넣는 경우 -->
<script>
class BankAccount{
//생성자 생성
constructor(name, balance){
this.name = name;
this.balance = balance;
}
deposit(amount){
this.balance += amount;
}
withdraw(amount){
this.balance -= amount;
}
transfer(amount, otherAccount){
this.balance -= amount;
otherAccount.balance += amount;
}
}
//객체 생성
let kimBank = new BankAccount('kim',0);
let hongBank = new BankAccount('hong',100);
console.log(kimBank);
console.log(hongBank);
//현재 내 계좌 출력 (이름:잔액)
console.log(kimBank.name, ':', kimBank.balance); // kim:0
//내 계좌에 입금
kimBank.deposit(500); // kim:500
console.log(kimBank.name, ':', kimBank.balance);
//내 계좌 출금
kimBank.withdraw(100); // kim:400
console.log(kimBank.name, ':', kimBank.balance);
//내 계좌에서 송금
kimBank.transfer(200,hongBank); // kim:200 hong:300
console.log(kimBank.name, ':', kimBank.balance);
console.log(hongBank.name, ':',hongBank.balance);
</script>