IT/JS

자바스크립트의 상속

프티 2021. 8. 25. 19:38
반응형

다음과 같은 생성자 함수가 있다고 해보자.

 

function Person(first, last, age, gender, interests) {
  this.name = {
    first,
    last
  };
  this.age = age;
  this.gender = gender;
  this.interests = interests;
};

Person.prototype.greeting = function() {
  alert('Hi! I\'m ' + this.name.first + '.');
};

 

그리고 Teacher라는 생성자 함수를 정의해보자.

 

function Teacher(first, last, age, gender, interests, subject) {
  Person.call(this, first, last, age, gender, interests);

  this.subject = subject;
}

 

Person은 call 메소드를 통해 Teacher에서 자신의 매개 변수를 사용할 수 있도록 한다.

이렇게 Teacher는 Person을 상속받게 되었다.

 

이외에 this.subject에 값을 할당하여 Teacher만의 속성을 만들었다.

 

위의 경우는 매개 변수를 가지는 생성자였다.

그렇다면 매개 변수를 가지지 않는 생성자는?

 

function Brick() {
  this.width = 10;
  this.height = 20;
}

function BlueGlassBrick() {
  Brick.call(this);

  this.opacity = 0.5;
  this.color = 'blue';
}

 

매개 변수를 가지지 않는 생성자 함수 Brick의 속성 width, height를 상속받기 위해서는

call 메소드에 this만 명시해주면 된다.

 

다시 Teacher로 돌아가 보자.

해당 생성자에는 자신에 대한 참조를 가지는 속성(this.subject)만이 할당되어 있다.

 

이는 콘솔에 다음 코드를 쳐보면 확인할 수 있다.

Object.getOwnPropertyNames(Teacher.prototype)
// Array[ "constructor"]

Object.getOwnPropertyNames(Person.prototype)
// Array[ "constructor", "greeting"]

 

이처럼 Teacher는 Person의 메소드를 상속받지 못하고 있다.

메소드를 상속받기 위해서 어떻게 해야 할까?

 

Teacher.prototype = Object.create(Person.prototype);

 

바로 Object.create()를 활용한다.

Object.create(proto[, propertiesObject])
- Object.create() 메소드는 지정된 프로토타입 객체 및 속성을 갖는 새 객체를 만든다.

 

그런데 이 경우 Teacher.prototype에 'Person.prototype을 상속받은 객체'를 할당하였기 때문에,

Teacher.prototype.constructor는 function Person이 된다.

 

따라서 추가적으로 다음의 코드를 작성한다.

Teacher.prototype.constructor = Teacher;

 

결과는 Teacher()를 반환할 뿐만 아니라 Person도 상속받게 된다.

 

 

반응형