[웹 개발 기초 자바스크립트] 14. Sub Class(Inheritance)

Shy·2023년 8월 30일
0

NodeJS(Express&Next.js)

목록 보기
15/39

Sub Class(Inheritance)

상속(Inheritance)은 객체 지향 프로그래밍의 주요 특성 중 하나로, 하나의 클래스가 다른 클래스의 속성과 메서드를 상속받을 수 있게 해준다. 이러한 상속 메커니즘을 통해 코드의 재사용성이 향상되고, 유지 관리가 쉬워진다.

JavaScript에서 ES6 이후로 class 키워드를 사용하여 클래스를 정의할 수 있으며, extends 키워드를 사용하여 상속을 구현할 수 있다. 상속받은 클래스를 "서브 클래스"(Sub Class) 또는 "하위 클래스"(Child Class)라고 부르고, 상속을 제공하는 클래스를 "슈퍼 클래스"(Super Class) 또는 "부모 클래스"(Parent Class)라고 부른다.

기본 문법

class Parent {
  constructor(name) {
    this.name = name;
  }

  greet() {
    console.log(`Hello, my name is ${this.name}.`);
  }
}

class Child extends Parent {
  constructor(name, age) {
    super(name);  // 부모 클래스의 constructor 호출
    this.age = age;
  }

  greet() {
    super.greet();  // 부모 클래스의 greet 메서드 호출
    console.log(`I am ${this.age} years old.`);
  }
}

const child = new Child('John', 10);
child.greet();
// 출력:
// Hello, my name is John.
// I am 10 years old.

주요 포인트

  1. Constructor: 서브 클래스에서 생성자(constructor)를 정의할 때, 반드시 super()를 호출하여 부모 클래스의 생성자를 실행해야 한다.
  2. Method Overriding: 서브 클래스는 부모 클래스의 메서드를 오버라이딩(재정의)할 수 있다. super 키워드를 사용하여 부모 클래스의 메서드를 호출할 수도 있다.
  3. Access to Parent Properties: 서브 클래스는 부모 클래스의 속성과 메서드에 접근할 수 있습니다. 이를 통해 코드의 재사용성이 높아진다.

상속은 클래스 간에 공통적인 속성이나 메서드를 재사용할 때 매우 유용하며, 코드의 구조를 체계적으로 만들 수 있다.

예제

class Person {
  constructor(name, email) {
    this.name = name;
    this.emial = email;
  }
  
  introduce() {
    return `Hello my name is ${this.name}`;
  }
}

class Client extends Person {
  constructor(name, email, phone, address) {
    super(name, email)
    
    this.phone = phone;
    this.address = address;
  }
}

const john = new Client('John', 'john@abc.com', '010-0000-1111', '서울');

console.log(john.introduce();)
// Hello my name is John

부모 클래스에게 상속받아 자식 클래스를 만들고, 자식 클래스에 부모 클래스의 속성을 불러올 때 super()를 사용한다.

John.introduce가 실행되는 순서

  1. client객체에 client.introduce가 있는지 확인
  2. 없기 때문에 Client.prototype에 있는지도 확인하지만 introduce가 없다.
  3. extends를 통해 관계가 만들어진 Client.prototype의 프로토타입인 Person.prototype에 메서드가 있는지 확인한다. 여기에 introduce가 있기 떄문에 이것을 사용한다.
profile
초보개발자. 백엔드 지망. 2024년 9월 취업 예정

0개의 댓글