-
JS / 객제 지향 프로그래밍 추상화,캡슐화,상속,다형성Web dev/JavaScript 2023. 4. 30. 19:12728x90반응형
1. 추상화(Abstraction)
가상의 존재를 프로그램 내에서 사용할 용도에 맞게 적절하게 설계하는 과정,
프로퍼티와 메소드의 이름을 누구나 이해하기 쉽게 잘 지어주거나 주석을 단다.
class User { constructor(email, birthdate) { // 사용자의 이메일 주소 this.email = email; // 사용자의 생일 this.birthdate = birthdate; } // 물건 구매하기 buy(item) { console.log(`${this.email} buys ${item.name}`); } }
2. 캡슐화(Encapsulation)
외부에서 프로퍼티나 메소드에 직접 접근할 수 없도록 함
class User { constructor(email, birthdate) { this.email = email; this.birthdate = birthdate; } buy(item) { console.log(`${this.email} buys ${item.name}`); } get email() { return this._email; } set email(address) { if (address.includes('@')) { this._email = address; } else { throw new Error('invalid email address'); } } } const user1 = new User('charlie123@google.com', '2000-12-05'); console.log(user1.email); // email이라는 getter 메소드 실행 user1.email = 'new123@google.com'; // email이라는 setter 메소드 실행 //캡슐화한 변수명에 직접 접근할수있기때문에 완벽한 캡슐화는 아니다. console.log(user1._email);
3. 상속(Inheritance)
부모 클래스의 프로퍼티와 메소드를 자식 클래스가 그대로 물려 받는 것
class User { constructor(email, birthdate) { this.email = email; this.birthdate = birthdate; } buy(item) { console.log(`${this.email} buys ${item.name}`); } } class PremiumUser extends User { constructor(email, birthdate, level) { super(email, birthdate); this.level = level; } streamMusicForFree() { console.log(`Free music streaming for ${this.email}`); } }
4. 다형성(Polymorphism)
다형성은 하나의 변수가 다양한 종류의 클래스로 만든 여러 객체를 가리킬 수 있음을 의미
class User { constructor(email, birthdate) { this.email = email; this.birthdate = birthdate; } buy(item) { console.log(`${this.email} buys ${item.name}`); } } class PremiumUser extends User { constructor(email, birthdate, level) { super(email, birthdate); this.level = level; } buy(item) { console.log(`${this.email} buys ${item.name} with a 5% discount`); } streamMusicForFree() { console.log(`Free music streaming for ${this.email}`); } } const item = { name: '스웨터', price: 30000, }; const user1 = new User('chris123@google.com', '19920321'); const user2 = new User('rachel@google.com', '19880516'); const user3 = new User('brian@google.com', '20051125'); const pUser1 = new PremiumUser('niceguy@google.com', '19891207', 3); const pUser2 = new PremiumUser('helloMike@google.com', '19900915', 2); const pUser3 = new PremiumUser('aliceKim@google.com', '20010722', 5); const users = [user1, pUser1, user2, pUser2, user3, pUser3]; users.forEach((user) => { user.buy(item); });
728x90반응형'Web dev > JavaScript' 카테고리의 다른 글
JS / swiper 옵션 정리 (0) 2023.06.11 JS / sort() 매서드로 정렬하기 (0) 2023.04.30 JS / 바닐라로 앵커트메뉴, 메뉴엑티브, 스티키 만들기 (0) 2023.04.23 JS / 바닐라로 sticky 스티키 메뉴 구현하기 (0) 2023.04.16 JS / 바닐라로 video play(), pause() 구현하기 (0) 2023.02.26