Front-End

vsoghlv@naver.com

자바스크립트 객체지향 프로그래밍 3

이번에는 클래스 기반의 상속을 확인해보자. 이전의 프로토타입을 이용한 상속과 비슷하지만 객체 리터럴 방식이 아닌 클래스 역할을 하는 함수를 만들어 상속을 구현한다.

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

Person.prototype.setName = function (value) {
  this.name = value;
};

Person.prototype.getName = function () {
  return this.name;
};

function Student(arg) {}

let you = new Person("Sun");
Student.prototype = you;

let me = new Student("Kim");
me.setName("Kim");
console.log(me.getName()); //Kim

Student 함수 객체를 만들어, 이 함수 객체의 프로토 타입이 Person 함수의 인스턴스를 참조하게 만들었다. 따라서 Student 함숫 객체로 생성된 me 의 prototype 링크가 생성자의 프로토타입 프로퍼티 Student.prototype 인 you 를 가리키고, new Person() 으로 만들어진 객체의 프로토타입 링크는 Person.prototype 을 가리키는 체인이 만들어진다.

위의 예제는 문제가 있는데 me 인스턴스를 생성할 때 부모 클래스의 생성자를 호출하지 않는다. 따라서 me 는 빈 객체로 호출된다. 이렇게 부모의 생성자가 호출되지 않으면, 인스턴스의 초기화가 제대로 이루어지지 않는다.

현재는 자식 클래스의 객체가 부모 클래스의 객체를 프로토타입 체인으로 접근하는데, 부모클래스의 인스턴스와 자식 클래스의 인스턴스는 서로 독립적일 필요가 있다.

두 클래스의 프로토타입 사이에 중개자를 만들어보자

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

Function.prototype.method = function (name, func) {
  this.prototype[name] = func;
};

Person.method("setName", function (value) {
  this.name = value;
});
Person.method("getName", function () {
  return this.name;
});

function Student(arg) {}

function F() {}

F.prototype = Person.prototype;
Student.prototype = new F();
Student.prototype.constructor = Student;
Student.super = Person.prototype;

let me = new Student();
me.setName("Kim");
console.log(me.getName()); //Kim

빈 함수 객체 F 를 중간에 두어 Person 과 Student 의 인스턴스를 서로 독립적으로 만들었다. 이렇게 함으로써 Person 함수 객체의 this 에 바인딩 되는 것은 Student 의 인스턴스에 접근할 수 없다.