본문 바로가기
TIL (Today I Learned)

TIL <6> 객체의 상속

by 튜브타고 둥둥 2020. 3. 25.

- 프로토타입을 이용한 상속 

> prototype : 자기 자신을 생성하기 위해 사용된 객체의 원형이며, prototype은 prototype object와 prototype link로 나누어볼 수 있다. prototype 속성은 prototype object를 가리키고, prototype object는 기본적인 속성으로 constructor와 __proto__를 가지고 있다.

> constructor : prototype object의 속성으로 원형 객체를 참조하고, prototype object 속성들을 그대로 상속받는 객체를 만드는 역할을 하는 함수이다.

> __proto__ : 상속받은 상위 객체의 prototype object에 연결해주며 prototype link라고도 한다. __proto__를 통해 상위 prototype object로 연결되어있는 형태를 prototype chain이라고 한다.

 

> Object.create()

지정된 프로토타입의 객체 및 속성을 상속받는 새로운 객체를 만든다.

Object.create()으로 만든 객체는 기존 constructor 연결이 끊어지고 Object.create()로 상속받은 객체와 연결이 되므로 자기 자신을 .constructor를 통해 다시 연결해주어야 한다.

 

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

Person.prototype.thisPerson = function() {
  return 'name:' + this.name + ', age:' + this.age;
};

function Worker(name, age, job) {
  Person.call(this, name, age)
  this.job = job;
}

Worker.prototype = Object.create(Person.prototype)
// (__proto__ : Person.prototype)을 Student.prototype.__proto__에 연결
Worker.prototype.constructor = Worker;

Worker.prototype.thisPerson2 = function() {
  return this.thisPerson() + ', job:' + this.job 
  // this.thisPerson()으로 Person.prototype.thisPerson을 그대로 가져와 사용하였다.
}

/* Worker.prototype.thisPerson = function() {
     return 'name:' + this.name + ', age:' + this.age + ', job:' + this.job
   }
   이렇게 thisPerson 자체를 오버라이딩하고 kim.thisPerson()를 실행해도 결과는 동일하며,
   Person의 thisPerson은 그대로이다.
   Person.prototype.thisPerson
   ƒ () {
     return 'name:' + this.name + ', age:' + this.age;
   } 
*/

var kim = new Worker('Eun', 25, 'Student');
console.log("kim.thisPerson2()", kim.thisPerson2());
// kim.thisPerson2() name:Eun, age:25, job:Student

 

- ES6 class & super

class :  객체를 생성하기 위한 함수로 class 선언 혹은 class 표현식으로 class를 생성

> constructor : 객체를 생성하고 초기화하기 위한 특수한 메소드

> super([arguments]) : 부모 생성자 호출

> super.functionOnParent([arguments]) : 부모 클래스의 해당 메소드 호출

 

class Person { // class 선언, class 표현식 ->  let Person = class { 
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
  thisPerson() {
      return 'name:' + this.name + ', age:' + this.age;
  }
};


class Worker extends Person {
    constructor(name, age, job) {
        super(name, age);
        this.job = job;
    }
    thisPerson() {
        return super.thisPerson() + ', job:' + this.job;
    }
};

var kim = new Worker('Eun', 25, 'Student');

console.log("kim.thisPerson()", kim.thisPerson());
// kim.thisPerson() name:Eun, age:25, job:Student

 

'TIL (Today I Learned)' 카테고리의 다른 글

REACT-NATIVE Android 환경설정  (0) 2020.06.04
TIL <4> Advanced Data Structure  (0) 2020.03.20