프로토타입 체인

YEN J·2022년 9월 21일
0

code states

목록 보기
17/43

프로토타입 체인

  • JavaScript에서 ‘상속’을 구현할 때 사용
    • 상속: 부모 클래스의 속성과 메서드를 자식 클래스가 물려받는 과정
    • extends와 super 키워드를 이용해서 상속 구현 가능

- 구현 예시

    //Human 클래스 생성
    class Human {  
        constructor(name, age) {
            this.name = name;
            this.age = age;
        }
        greeting() {
            console.log(`Hi! I'm ${this.name}.`);
        }
    } 
    // Author 클래스는 Human 클래스로부터 상속받음(extends 키워드 사용)
    // 부모 클래스의 생성자 참조(super 키워드 사용)
    class Author extends Human { 
        constructor(name, age, bookname, publisher){
            super(name, age); 
            this.bookname = bookname;
            this.publisher = publisher;
        }
    }
    let author1 = new Author('Hermann Hesse', 120, 'demian', 'Harper Perennial'); // Author 클래스의 새로운 인스턴스를 변수 author1에 할당
    author1.greeting(); // 부모 클래스의 메서드 접근 가능
    author1.name; // 부모 클래스의 속성 접근 가능
    author1.bookname; // 자식 클래스에서 추가한 속성 접근 가능
  • div요소의 프로토타입 체인 확인하기
    • div -> HTMLDivElement -> HTMLElement -> Element -> Node -> EventTarget -> Object 순
    • Object는 모든 클래스의 조상

0개의 댓글