본문 바로가기
JavaScript

JavaScript 프로토타입 체인

by 이히힣 2022. 7. 25.

[프로토타입 체인]

 

JavaScript 객체 지향 프로그램에서 상속을 구현할 때 사용한다.

 

상속:  부모 클래스의 속성과 메서드를 자식 클래스가 물려받는 것

 

 

 

class 구문은 새로운 클래스를 작성함을 의미한다. Class 블록 내에서 모든 기능을 정의할 수 있다.

 

class Person {
  constructor(first, last, age, gender, interests) {
    this.name = {
      first,
      last
    };
    this.age = age;
    this.gender = gender;
    this.interests = interests;
  }

  greeting() {
    console.log(`Hi! I'm ${this.name.first}`);
  };

  farewell() {
    console.log(`${this.name.first} has left the building. Bye for now!`);
  };
}

 

 

new연산자로 객테 인스턴스를 생성 할 수 있다.

 

let han = new Person('Han', 'Solo', 25, 'male', ['Smuggling']);
han.greeting();
// Hi! I'm Han

let leia = new Person('Leia', 'Organa', 19, 'female' ['Government']);
leia.farewell();
// Leia has left the building. Bye for now

 

 

 

자바스크립트에서는 extends 와 super 키워드를 이용해서 상속을 구현할 수 있다.

 

[extends]

 

클래스를 다른 클래스의 자식으로 만들기 위해 class선언 또는 class식에 사용된다.

 

 

extends 사용

Polygon 클래스로부터 Square 클래스를 만드는 법

 

class Square extends Polygon {
  constructor(length) {
    // 여기서, length와 함께 부모 클래스의 생성자를 호출
    // Polygon의 너비 및 높이가 제공됨
    super(length, length);
    // 주의: 파생 클래스에서, super()가 먼저 호출되어야 'this'를
    // 사용할 수 있습니다. 이를 빼먹으면 참조 오류가 발생합니다.
    this.name = 'Square';
  }

  get area() {
    return this.height * this.width;
  }

  set area(value) {
    this.area = value;
  }
}

 

 

내장 객체에서 사용

내장 객체 Date를 확장한다.

 

class myDate extends Date {
  constructor() {
    super();
  }

  getFormattedDate() {
    var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
    return this.getDate() + "-" + months[this.getMonth()] + "-" + this.getFullYear();
  }
}

 

 

null 확장

prototype 객체가 Object.prototype 으로부터 상속받지 않은 것을 제외하면 보통 클래스처럼 동작한다.

 

class nullExtends extends null {
  constructor() {}
}

Object.getPrototypeOf(nullExtends); // Function.prototype
Object.getPrototypeOf(nullExtends.prototype) // null

 

 

 

[super]

 

super 키워드는 부모 오브젝트의 함수를 호출할 때 사용된다.

 

생성자에서는 super 키워드 하나만 사용되거나 this 키워드가 사용되기 전에 호출되어야 하고,

super 키워드는 부모 객체의 함수를 호출하는데 사용될 수 있다.

 

 

클래스에서 super 사용

 

class Polygon {
  constructor(height, width) {
    this.name = 'Polygon';
    this.height = height;
    this.width = width;
  }
  sayName() {
    console.log('Hi, I am a ', this.name + '.');
  }
}

class Square extends Polygon {
  constructor(length) {
    this.height; // 참조오류가 발생합니다. super가 먼저 호출되어야 합니다.

    // 여기서, 부모클래스의 생성자함수를 호출하여 높이값을 넘겨줍니다.
    // Polygon의 길이와 높이를 넘겨줍니다.
    super(length, length);

    // 참고: 파생 클래스에서 super() 함수가 먼저 호출되어야
    // 'this' 키워드를 사용할 수 있습니다. 그렇지 않을 경우 참조오류가 발생합니다.
    this.name = 'Square';
  }

  get area() {
    return this.height * this.width;
  }

  set area(value) {
    this.area = value;
  }
}

 

 

정적(static) 메서드에서 super 호출

 

class Human {
  constructor() {}
  static ping() {
    return 'ping';
  }
}

class Computer extends Human {
  constructor() {}
  static pingpong() {
    return super.ping() + ' pong';
  }
}
Computer.pingpong(); // 'ping pong'

 

 

  • delete 연산자를 사용할 수 없으며 super.prop 또는 super[expr] 표현식을 사용하여 부모 클래스의 속성을 삭제할 경우 Refference Error 오류가 발생한다.
  •  super.prop은 non-writable 속성 값을 덮어 쓸 수 없다.
 

 

 

 

[DOM과 프로토타입]

 

DOM을 이용해 document.createElement('div')로 새로운 div 엘리먼트를 만들면 생성된 div 엘리먼트는, HTMLDivElement라는 클래스의 인스턴스이다.

 

 

 

__proto__를 이용하면 부모 클래스의 프로토타입, 혹은 '부모의 부모 클래스'의 프로토타입을 탐색할 수 있다.

 

 

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__
// {constructor: ƒ, __defineGetter__: ƒ, __defineSetter__: ƒ, hasOwnProperty: ƒ, __lookupGetter__: ƒ, …}
div.__proto__.__proto__.__proto__.__proto__.__proto__.__proto__.__proto__
// null
 
 

 

 

 


   ⭐️⭐️⭐️중요⭐️⭐️⭐️

 

  • JavaScript는 프로토타입 기반 언어이며 OOP 상속을 구현할 때 프로토타입 체인을 사용한다.
  • DOM은  상속 관계로 이루어져 있으며  __proto__ 를 활용하여 상속 관계를 확인할 수 있다.

 

 


 

🌈 참고

 

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Classes/extends

 

extends - JavaScript | MDN

extends 키워드는 클래스를 다른 클래스의 자식으로 만들기 위해 class 선언 또는 class 식에 사용됩니다.

developer.mozilla.org

 

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/super

 

super - JavaScript | MDN

super 키워드는 부모 오브젝트의 함수를 호출할 때 사용됩니다.

developer.mozilla.org

 

'JavaScript' 카테고리의 다른 글

JavaScript 프로토타입 체인 실습  (0) 2022.07.25
npm version update 하는 법  (0) 2022.07.25
JavaScript 프로토타입  (0) 2022.07.23
JavaScript 객체 지향 프로그래밍  (0) 2022.07.22
JavaScript 클래스와 인스턴스  (0) 2022.07.22