<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>class ex</title>
<!-- 은행 -->
</head>
<body>
<!-- 하나씩 넣는 경우 -->
<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>
<!-- 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>
</body>
</html>
'JS > JS 수업분' 카테고리의 다른 글
[JS] day09_Math_random (0) | 2023.04.18 |
---|---|
[JS] day11_Lotto과제 (0) | 2023.04.18 |
[JS] day11_class, 객체, 생성자 (0) | 2023.04.18 |
[JS] day11_mapEx (0) | 2023.04.18 |
[JS] day11_count생성 (더하기 버튼 : +1 / 빼기버튼 : -1) (0) | 2023.04.18 |