JavaScript 객체 지향 - 생성자를 통한 상속

김민재·2021년 7월 10일
0


-부모 constructor funcion인 Person객체와 그 Person의 prototype 객체가 존재하며 서로가 상호 참조하고 있다.
-마찬가지로 constructor funcion PersonPlus객체와 자신의 prototype 객체가 있고 서로 상호 참조하고 있는 상황이다.

-PersonPlus객체를 기반으로 하여 new연산자를 이용하여 kim이라는 객체를 만든다.
-kim객체의 __proto__라는 프로퍼티가 자신을 생성한 생성자 함수의 prototype 프로퍼티가 가르키고 있는 객체, 즉 PersonPlus의 prototype객체를 가르키게 된다.

-이 상태에서 kim.avg()를 호출하면 kim이라는 객체의 avg프로퍼티가 없으면 __proto__를 따라 PersonPlus의 prototype객체에 avg가 있는지 확인한 뒤 실행이 된다.
-kim.sum()을 호출하면 kim 객체에도 없고 PersonPlus의 prototype객체에도 없기 때문에 에러가 발생한다.

-Person이라는 constructor funcion에 prototype객체에 있는 sum이라는 메소드를 호출하도록 하고자 한다.
-PersonPlus의 prototype객체에 __proto__ 프로퍼티가 Person의 prototype객체를 가리키게 하면 된다.

  • constructor 프로퍼티는 어떠한 객체가 누구로부터 만들어졌는지를 알려주는 역할을 한다.

    -new 연산자를 통해서 새로운 객체를 constructor function이 뭔지 몰라도 만들어낼 수 있기도 하다.

-생성자를 통한 상속과의 비교

<script>
function Person(name, first, second){
  this.name = name;
  this.first = first;
  this.second = second;
}
Person.prototype.sum = function(){
// person을 이용하여 만들어진 모든 객체에서 공유하는 sum메소드 생성
  return this.first+this.second;
}
//Person, constructor function 상속한 생성자
function PersonPlus(name, first, second, third) {
  Person.call(this, first, second)
//Person함수의 call메소드를 실행하여 PersonPlus 생성자가 new를 통해 만들어지는 객체인 this를 첫 번째 인자로 넣어준다.
this.third = third;
}
PersonPlus.prototype = Object.create(Person.prototype)
//Person.prototype객체를 __proto__로 하는 새로운 객체가 만들어진다. 
//새로운 객체는 __proto__가 Person을 가르키게 된다.
//그러나 새로운 객체로 PersonPlus.prototype을 대체해버린다. 
//그렇기에 Person.prototype.constructor를PersonPlus로 대입해줘야한다.
Person.prototype.constructor = PersonPlus;
//PersonPlus.prototype.__proto__ = Person.prototype; 이 방식은 __proto__만 바꾸는 것이다.__proto__는 비표준이기에 사용하질 않는다.
PersonPlus.prototype.avg = function(){
  return (this.first+this.second+this.third)/3;
}
const k = new PersonPlus('kim',10, 20, 30);
console.log('k.sum()', k.sum());
console.log('k.avg()', k.avg());
</script>

-class를 통한 상속과의 비교

<script>
class Person{
//function Person(name, first, second)과 같다.
  constructor(name, first, second){
    this.name = name;
    this.first = first;
    this.second = second;
  }
  sum() {
    return this.first+this.second+this.third;
  //Person.prototype.sum = function(){return this.first+this.second;}과 같은 맥락
  }
}
class PersonPlus extends Person{
  constructor(name, first, second, third){
    super(name, first, second, third);
  //Person.call(this, first, second)과 같은 맥락
    this.third = third;
  }
  sum() {
    return super.sum()+this.third;
  }
  avg() {
    return (this.first+this.second+this.third)/3;
  }
}
const k = new PersonPlus('kim',10, 20, 30);
console.log('k.sum()', k.sum());
console.log('k.avg()', k.avg());
</script>

결론

실 사용은 constructor를 통한 상속 보단 class 상속을 이용하되 prototype과 __proto__의 관계를 꼭 이해하자 !

profile
자기 신뢰의 힘을 믿고 실천하는 개발자가 되고자합니다.

0개의 댓글