객체와 객체지향 프로그래밍(Object-Oriented Programming)

Wonhyo LEE·2022년 3월 30일
0

여기서 Checking (예금 계좌) 이라는 객체를 만들었고, 생성자를 통해서 this 키워드를 통해 balance 라는 객체의 속성에 값을 할당 받을 수 있습니다. 그리고 Checking 계좌에는 deposit() , withdraw() , toString() 이라는 메소드를 통해 계좌를 관리하거나, 계좌 정보를 출력할 수 있습니다.

function Checking(amount) {   
    this.balance = amount; // 속성   
    this.deposit = deposit; // 메소드(함수)   
    this.withdraw = withdraw; // 메소드(함수)   
    this.toString = toString; // 메소드(함수)
}

이와 같이 메소드를 선언하면 Checking 이라는 객체에 this라는 키워드를 통해 속성에 접근 할 수 있습니다.

function deposit(amount) { //입금
    this.balance += amount; 
}

function withdraw(amount) { //출금
    if (amount <= this.balance) { //잔액 여유 시
        this.balance -= amount;   
    }   
    if (amount > this.balance) { //잔액 부족 시
        print("잔액 부족");   
    } 
}

function toString() { //잔고 표시
    return "잔고: " + this.balance; 
}

사용 방법

var account = new Checking(500); 
account.deposit(1000); 
console.log(account.toString()); //"잔고: 1500"
account.withdraw(750); 
print(account.toString()); // "잔고: 750" 
account.withdraw(800); // "잔액 부족"
print(account.toString()); // 잔고: 750
profile
프론트마스터를 꿈꾸는...

0개의 댓글