1 minute read

2022.11.20

💡 오늘의 JavaScript 공부

▶️ 프로토타입

자바스크립트는 프로토타입 기반 언어이다. 여기서 프로토 타입은 원형 객체를 의미한다.

class Human {
    constructor(name,age){
        this.name = name;
        this.age = age;
    }
    sleep(){
        console.log(`${this.name}은 잠에 들었습니다.`)
    }
}

let sehoonKim = new Human('김세훈',30)

console.log(Human.prototype.constructor === Human) // true
console.log(Human.prototype === sehoonKim.__proto__) // true
console.log(Human.prototype.sleep === sehoonKim.sleep) // true
📌 Human 이라는 클래스와 인스턴스 그리고 프로토타입의 관계

스크린샷 2022-11-21 11 37 16

class Human {
  constructor(name, age){
    this.name = name;
    this.age = age;
  }
  sleep(){
    return `${this.name}이 잠을 잡니다.`
  }
}
let steve = new Human('steve', 20);
steve.sleep() // 'steve이 잠을 잡니다.'

steve.__proto__ === Human.prototype // true
Human.prototype.constructor === Human // true
📌 Human 이라는 클래스와 인스턴스 그리고 프로토타입의 관계

스크린샷 2022-11-21 11 37 28

📌 프로토타입 체인

객체 지향 프로그래밍의 특성 중 상속을 js에서 구현할 때에는 프로토타입 체인을 사용한다.

예를들어

let kimcoding = new Human('김코딩', 30);
// 속성
kimcoding.age;
kimcoding.gender;
// 메서드
kimcoding.eat();
kimcoding.sleep();

//-----------------------------------------------
  
let parkhacker = new Student('박해커', 22);
// 속성
parkhacker.grade;
// 메서드
parkhacker.learn();

위 예시에서 나타나는 박해커(parkhacker)는 Student이다. 박해커가 학생이라고 해서, age나 gender와 같은 속성이 존재하지 않거나, sleep() 이나 eat() 이라는 메서드를 사용할 수 없는가? 그렇지 않다. Student는 Human의 특징을 그대로 물려받는다. 속성과 메서드를 물려주는 클래스를 부모 클래스(여기서는 Human), 속성과 메서드를 물려받는 클래스를 자식 클래스(여기서는 Student), 그리고 이 과정을 상속이라고 한다.

📌 DOM과 프로토타입

브라우저에서 DOM을 이용하면, document.createElement('div')로 새로운 div 엘리먼트를 만들 수 있다. 이렇게 생성된 div 엘리먼트는, HTMLDivElement라는 클래스의 인스턴스이다.

DOM 엘리먼트는 예를 들어 innerHTML과 같은 속성, 또는 append()와 같은 메서드가 있다. 각각의 엘리먼트가 해당 메서드나 속성이 있다는 것을 통해, Element라는 공통의 부모가 있음을 알 수 있다.

스크린샷 2022-11-21 11 43 23

화살표 방향은 부모를 가리킨다. EventTarget의 부모로는, 모든 클래스의 조상인 Object가 존재한다.

let div = document.createElement('div');

div.__proto__.__proto__                // HTMLElement
div.__proto__.__proto__.__proto__      // Element

Comments