[JavaScript] 객체 지향 프로그래밍(OOP) - 2

Date:

카테고리:

태그:

1. 클래스를 사용한 객체 지향

  1. 넘버링
  • 내용
class Person{
  constructor(name, first, second) {
    this.name = name;
    this.first = first;
    this.second = second;
  }
  sum(){
    return this.first + this.second;
  }
  // class에서는 function 표현 없이 메서드 정의
  // 기존 class 없이 구현한 것과 같은 코드(아래)
}
let kim = new Person('kim', 10, 20) 
kim.sum = function(){
   return this.first + this.second
}
let lee = new Person('kim', 10, 30)

console.log(kim.sum())  // 30
console.log(lee.sum())  // 40
  • 클래스 없이 구현한 기존 코드
function Person(name, first, second){
   this.name=kim;
   this.first=first;
   this.second=second;
}

Person.prototype.sum = function() {
   return this.first + this.second
}
(...)

2. 상속

  1. 상속을 통한 효율적 코드 작성

    • 부모 클래스에 있는 내용 중복 피할 수 있음(메모리 효율성)
    • 부모 클래스에 없는 기능 추가 가능
    • 부모 클래스가 수정이 불가하거나 어려울 때도 활용 가능
class Person{
  constructor(name, first, second) {
    this.name = name;
    this.first = first;
    this.second = second;
  }
  sum(){
    return this.first + this.second;
  }
}

class PersonPlus extends Person{
// extends를 활용해 Person 클래스에서 상속 받음
// 부모 객체에 있는 프로퍼티, 메서드 상속 받음
  avg(){
    return (this.first+this.second)/2
  }
  // 변화 원하는 부분만 추가하여 활용 가능
  // 상속
}
  • 상속을 쓰지 않는다면 비슷한 클래스 생성 시 코드 중복
class Person{
  constructor(name, first, second) {
    this.name = name;
    this.first = first;
    this.second = second;
  }
  sum(){
    return this.first + this.second;
  }
}

class PersonPlus{
  constructor(name, first, second) {
    this.name = name;
    this.first = first;
    this.second = second;
  }
  sum(){
    return this.first + this.second;
  }
  avg(){
    return (this.first+this.second)/2;
  }
}

3. super의 활용

  • super는 부모/자식 간의 중복을 줄여줌
  • super() : 부모클래스의 constructor에 접근
  • super.메서드명 : 부모클래스의 메서드를 가져다 씀
class Person{
    constructor(name, first, second){
        this.name = name;
        this.first = first;
        this.second = second;
    }
    sum(){
        return this.first+this.second;
    }
}
class PersonPlus extends Person{
    constructor(name, first, second, third){
        super(name, first, second);
        //super() 부모클래스의 생성자가 호출 된다
        this.third = third;
    }
    sum(){
        return super.sum()+this.third;
        //super. 부모클래스 자체를 뜻한다. 메서드 활용 가능
    }
    avg(){
        return (this.first+this.second+this.third)/3;
    }
}

JavaScript 카테고리 내 다른 글 보러가기

댓글 남기기