ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 프로토타입 체인
    블로깅 과제 2022. 11. 21. 12:07

    생성자 함수인 class를 정의하고 instance를 생성하는데 상속을 배웠다. 이것은 브라우저가 알아서 처리해주는 방법이었다. 그렇다면 우리가 객체를 생성하고 상속받으려면 어떻게 해야할까? 바로 정답은 프로토타입 체인이다. 객체지향 프로그래밍의 특성 중 상속을 js에서 구현할 때는 프로토타입 체인을 사용하기 때문이다. 

     

    1. 부모가 될 객체에서 속성 받아오기

    부모가 될 객체에서 속성을 받아오는 방법은 call()이라는 메소드를 사용하는 것이다. 

    // 부모가 될 객체
    function Human (name, age) {
        this.name = name;
        this.age = age;
      }
      
      Human.prototype.eat = function() {
        console.log(`${this.name}은 밥을 먹습니다`);
      }
    
      Human.prototype.sleep = function() {
        console.log(`${this.name}은 잠에 들었습니다`);
      }
    }
    
    // 자식이 될 객체
    function Student (name, age, grade) {
        Human.call(this, name, age) // 동일한 속성들을 call()의 인자로 전달
        this.grade = grade;
    }

    call()을 이용하여 부모가 될 Human 생성자 함수에 있는 필요한 매개변수를 call()의 인자로 전달받았다. Human 생성자 함수에 없는 매개변수는 this를 이용하여 할당해준다.

     

    2. 부모 객체에서 메서드 상속받기

     부모 객체로부터 속성은 상속받았지만 아직 메서드는 받지 못했다. 메서드는 prototype에 저장이 되기 때문이다. 그래서 Human.prototype을 새로 만들어 Student.prototype에 할당해 줄 필요가 있다. 이때 Object.create를 사용해주면 된다.

    Student.prototype = Object.create(Human.prototype)
    // Human.prototype에 있는 요소를 새로운 객체에 복사

    위와같이 할당해주면 Human.prototype의 요소를 가진 새로운 객체가 Student.prototype의 값에 할당되어 Human.prototype에 있는 모든 메소드를 사용할 수 있게 되었다.

    하지만 Student.prototype.constructor는 Human()을 나타낸다. Student.prototype가 Human.prototype의 값을 할당했기 때문이다. Student.prototype.constructor를 Student로 재할당 해주면 된다.

     

    3. 메서드 추가하기

    Student.prototype.learn = function() {
      console.log(`${this.name}은 공부하고 있습니다`);
    }

    위와 같이 객체안에 key와 값을 넣는 것과 같이 해주면 Student.prototype에 메서드가 추가되어 learn() 메소드를 사용할 수 있게 된다.

     

    4. ES6에서는?

    ES6에서는 extends와 super를 사용하면 더 간편하게 상속시킬 수 있다.

    // 부모가 될 객체
    class Human {
      constructor(name, age) {
        this.name = name;
        this.age = age;
      }
      
      eat() {
        console.log(`${this.name}은 밥을 먹습니다`);
      }
    
      sleep() {
        console.log(`${this.name}은 잠에 들었습니다`);
      }
    }
    
    // 자식이 될 객체
    class Student extends Human {
      constructor(name, age, grade){
        super(name, age) // 동일한 속성들을 super의 인자로 전달
        this.grade = grade;
      }
    }

    위와 같이 사용해주면 속성뿐만 아니라 메소드 또한 상속되어 사용이 가능하다.

     

    4. ES6로 상속받은 객체의 .__proto__ 값은?

    ES6로 상속받은 객체의 .__proto__ 값은 생성자 함수 Human이었다. prototype이 아닌 객체에서 바로 상속을 받아왔기 때문이 아닐까 생각해본다.

     

    5. DOM prototype?

    DOM의 트리구조 또한 프로토 타입 체인으로 이어져 있었다.

    let div = document.createElement('div');
    
    div.__proto__  // HTMLDivElement
    div.__proto__.__proto__  // HTMLElement
    div.__proto__.__proto__.__proto__  // Element 
    div.__proto__.__proto__.__proto__.__proto__  // Node
    div.__proto__.__proto__.__proto__.__proto__.__proto__  // EventTarget
    div.__proto__.__proto__.__proto__.__proto__.__proto__.__proto__  // object
    div.__proto__.__proto__.__proto__.__proto__.__proto__.__proto__.__proto__ //null

    '블로깅 과제' 카테고리의 다른 글

    UI/UX  (0) 2022.12.19
    REST API  (0) 2022.12.02
    프로토 타입(object prototype)  (0) 2022.11.18
    객체 지향 프로그래밍  (0) 2022.11.18
    클래스(class)와 인스턴스 객체(instance object)  (0) 2022.11.18
Designed by Tistory.