자바스크립트에서 클래스 확장(상속)하는 방법은 무엇인가요?


자바스크립트에서 클래스를 확장(상속)하는 방법은 extends 키워드를 사용하는 것입니다.

예를 들어, 부모 클래스인 Animal 클래스가 있고, 이를 상속받는 자식 클래스인 Dog 클래스를 만들고 싶다면 다음과 같이 작성할 수 있습니다.

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

  speak() {
    console.log(`${this.name} makes a noise.`);
  }
}

class Dog extends Animal {
  constructor(name) {
    super(name);
  }

  speak() {
    console.log(`${this.name} barks.`);
  }
}

const d = new Dog('Mitzie');
d.speak(); // 출력 결과: "Mitzie barks."

위의 예제에서 Dog 클래스는 Animal 클래스를 상속받았습니다. extends 키워드를 사용하여 Dog 클래스가 Animal 클래스를 확장하도록 지정하였습니다. super 키워드를 사용하여 부모 클래스의 생성자를 호출하고, 자식 클래스에서 추가적으로 필요한 속성이나 메소드를 정의할 수 있습니다.

또 다른 방법으로는 Object.create() 메소드를 사용하여 상속을 구현할 수 있습니다. 이 방법은 extends 키워드를 사용하는 것보다 더 복잡하고 번거로우므로 자주 사용되지는 않습니다.



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.