[javascript] 프로토타입 체인에서 메소드 상속의 한계

자바스크립트는 프로토타입 기반 언어로, 객체의 프로퍼티 및 메소드를 상속하는데 사용되는 프로토타입 체인을 가지고 있습니다. 이는 간단하면서도 강력한 상속 방식으로, 하나의 객체가 다른 객체로부터 프로퍼티 및 메소드를 상속받을 수 있게 해줍니다. 하지만 이런 프로토타입 기반의 상속은 몇 가지 한계를 가지고 있습니다.

1. 메소드 상속의 한계

프로토타입 체인을 이용하여 메소드를 상속받을 때, 동적으로 바인딩된 this의 문제가 발생할 수 있습니다. 예를 들어, 하위 객체에서 상속받은 메소드를 호출할 때, this의 참조가 원치 않는 객체를 가리킬 수 있습니다.

아래의 예시를 살펴봅시다.

function Person(name) {
  this.name = name;
}

Person.prototype.introduce = function() {
  return `Hello, I'm ${this.name}.`;
};

function Employee(name, title) {
  this.name = name;
  this.title = title;
}

Employee.prototype = new Person();

Employee.prototype.introduce = function() {
  return `Hello, I'm ${this.name} and I'm a ${this.title}.`;
};

const employee = new Employee('Alice', 'Manager');
console.log(employee.introduce()); // 결과: Hello, I'm Alice and I'm a Manager.

위 예시에서, Employee 객체의 introduce 메소드 내부에서 this는 Employee 객체를 참조해야 하지만, 실제로는 Person 객체를 가리키게 됩니다.

이러한 한계를 극복하기 위해, ES6에서는 classextends 키워드를 이용한 클래스 기반의 상속이 도입되었습니다. 클래스 기반의 상속은 프로토타입 상속의 이러한 문제를 해결하고, 보다 명확하고 안정적인 상속 방식을 제공합니다.

2. 클래스 기반 상속의 활용

ES6에서 도입된 클래스 기반 상속을 활용하여 위 예시를 다시 작성해 보겠습니다.

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

  introduce() {
    return `Hello, I'm ${this.name}.`;
  }
}

class Employee extends Person {
  constructor(name, title) {
    super(name);
    this.title = title;
  }

  introduce() {
    return `Hello, I'm ${this.name} and I'm a ${this.title}.`;
  }
}

const employee = new Employee('Alice', 'Manager');
console.log(employee.introduce()); // 결과: Hello, I'm Alice and I'm a Manager.

위 예시에서, extends 키워드를 사용하여 Employee 클래스가 Person 클래스를 상속받도록 정의했습니다. 이를 통해 클래스 기반의 상속 방식을 사용함으로써, 프로토타입 체인에서 발생할 수 있는 메소드 상속의 문제를 해결할 수 있습니다.

프로토타입 기반의 상속이 가진 한계를 이해하고, 이를 극복하는 데 필요한 도구 및 기술을 습득하는 것은 자바스크립트 개발자로서 중요한 과제입니다.

자바스크립트에서 상속에 대한 더 자세한 내용은 MDN 웹 문서 Inheritance and the prototype chain을 참고하시기 바랍니다.