JavaScript 객체 지향 - 객체 간의 상속

김민재·2021년 7월 10일
0

객체 간의 상속

-sub 객체는 super 객체의 기능을 상속받으면서 기능을 추가하고 싶은 객체이다.
-sub 객체는 super 객체로부터 직접 기능을 상속받을 수 가 있다. 즉 객체가 직접 다른 객체에 상속을 받을 수 도 있고 그 상속관계를 바꿀 수 도 있다.

-다른 객체에 상속을 받고싶을 땐 prototype link를 바꾸면된다.
-sub 객체의 prototype link가 가르키고 있는 객체를 prototype object라고도 부른다.

proto와 Object.create

  • proto속성을 걸어줌으로서 subObj가 superObj의 자식임을 알려주는 링크를 걸어준다.
  • 이렇게 js는 클래스가 아닌 인스턴스, 즉 객체를 직접 다른객체의 자식으로 만들 수 있다.
<script>
const superObj = {superVal:'super'}
const subObj = {subVal:'sub'}
subObj.__proto__ = superObj;
console.log('subObJ.subVal =>', subObj.subVal);
console.log('subObJ.superVal =>', subObj.superVal);
//subObJ.subVal => sub
//subObJ.superVal => super
subObj.superVal = 'sub';
// subObj에 상속받은 superObj의 객체의 값만 바뀐다.
console.log('subObJ.superVal =>', subObj.superVal);
//subObJ.superVal => sub
</script>
  • Object.create 메소드를 사용하면 새로운 객체를 만들 수 있다.
  • 새로운 subObj 객체는 Object.create(), ()속 상위객체인 superObj를 부모로한다.
<script>
const superObj = {superVal:'super'}
const subObj = Object.create(superObj);
debugger;
subObj.subVal = 'sub'
console.log('subObJ.subVal =>', subObj.subVal);
console.log('subObJ.superVal =>', subObj.superVal);
</script>

-proto로 기존의 코드를 구현한 방법

<script>
const kim =  {
  name : 'kim',
  first:10, second:20,
  sum:function(){return this.first+this.second}
}
const min = {
  name : 'min',
  first:10, second:10,
  avg:function(){
    return this.first+this.second/2
  }
}
min.__proto__ = kim;
console.log(min.sum());
console.log(min.avg());
</script>

-object.create로 기존의 코드를 구현한 방법

<script>
const kim =  {
  name : 'kim',
  first:10, second:20,
  sum:function(){return this.first+this.second}
}
const min = Object.create(kim);
min.name = 'min'
min.first = 10;
min.second = 10;
min.avg = function(){
  return this.first + this.second/2
}
console.log(min.sum());
console.log(min.avg());
</script>
profile
자기 신뢰의 힘을 믿고 실천하는 개발자가 되고자합니다.

0개의 댓글