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>
'JS > JS 예시' 카테고리의 다른 글
[JS] 가위바위보 게임 (0) | 2023.04.19 |
---|---|
[JS] lotto번호 생성 / 출력 (set, [ ] 이용) (0) | 2023.04.18 |
[JS] Map 예제 : 과목, 점수를 map에 저장하고 합계,평균 등 출력 (0) | 2023.04.18 |
[JS] Count버튼 만들기 (더하기버튼누르면 +1/ 뺴기버튼누르면 -1) (0) | 2023.04.18 |
[JS] 업다운 게임 (0) | 2023.04.17 |