Computer >> 컴퓨터 >  >> 프로그래밍 >> JavaScript

JavaScript에서 자식 클래스가 부모와 같은 이름의 메서드를 가질 때 부모 메서드 호출하는 방법

JavaScript에서 상속 관계에 있을 때 부모 클래스와 자식 클래스가 같은 이름과 시그니처를 가진 메서드를 정의하고 있다면, 기본적으로 자식 객체는 오버라이딩된 자신의 메서드를 호출하게 됩니다. 이런 상황에서 부모 클래스의 원본 메서드를 직접 호출해야 할 때가 있습니다.

부모 메서드를 호출하는 문법

이 경우 prototypecall() 메서드를 조합하여 아래와 같은 문법으로 부모의 메서드를 호출할 수 있습니다.

console.log(부모클래스이름.prototype.메서드이름.call(자식객체이름));

예제 코드

다음 예제는 Super(부모) 클래스와 Child(자식) 클래스가 동일한 이름의 display() 메서드를 가지고 있을 때, 각각의 메서드를 호출하는 방법을 보여줍니다.

class Super {
   constructor(value) {
      this.value = value;
   }
   display() {
      return `부모 클래스의 값은 = ${this.value}`;
   }
}
class Child extends Super {
   constructor(value1, value2) {
      super(value1);
      this.value2 = value2;
   }
   display() {
      return `${super.display()}, 자식 클래스의 value2 값은 = ${this.value2}`;
   }
}
var childObject = new Child(10, 20);
console.log("부모 메서드 display() 호출=")
console.log(Super.prototype.display.call(childObject));
console.log("자식 메서드 display() 호출=");
console.log(childObject.display());

코드 실행 방법

위 프로그램을 실행하려면 다음 명령어를 사용합니다.

node 파일이름.js

여기서는 파일 이름이 demo192.js라고 가정합니다.

실행 결과

위 코드를 실행하면 다음과 같은 출력 결과를 확인할 수 있습니다.

PS C:\Users\Amit\javascript-code> node demo192.js
부모 메서드 display() 호출= 부모 클래스의 값은 = 10
자식 메서드 display() 호출= 부모 클래스의 값은 = 10, 자식 클래스의 value2 값은 =20

핵심 정리

Super.prototype.display.call(childObject) 구문은 부모 클래스의 프로토타입에 정의된 display() 메서드를 가져오되, this 컨텍스트를 자식 객체로 바인딩하여 실행합니다. 덕분에 자식 객체의 데이터를 기반으로 부모의 로직을 그대로 수행할 수 있습니다. 또한 자식 클래스 내부에서는 super.display()처럼 super 키워드를 사용하면 간편하게 부모 메서드를 호출할 수 있다는 점도 함께 기억해 두면 좋습니다.