코드스테이츠

1/16 일일정리 프로토타입

강물둘기 2023. 1. 16. 14:48

1/13에 이어서 프로토타입을 학습했다. 중간에 끊기 애매해서 여기에 정리

Prototype?

Javascript는 prototype 기반의 언어다. 프로토타입(prototype)은 어떤 객체의 상위(부모) 객체의 역할을 하는 객체로서 다른 객체에 공유 프로퍼티(매서드 포함)를 제공한다.(상속)

class Person {
  constructor(name) {
    this.name = name;
  }

  sayHi() {
    console.log(`Hi! My name is ${this.name}`);
  }
}

const me = new Person('Lee');
me.sayHi(); // Hi! My name is Lee

// me 객체의 프로토타입은 Person.prototype이다.
Object.getPrototypeOf(me) === Person.prototype; // -> true
me instanceof Person; // -> true

// Person.prototype의 프로토타입은 Object.prototype이다.
Object.getPrototypeOf(Person.prototype) === Object.prototype; // -> true

Javascript는 프로토타입을 기반으로 상속을 구현해서 불필요한 중복을 제거한다. 상속은 코드의 재사용이란 관점에서 매우 유용하다. 생성자 함수가 생성할 모든 인스턴스가 공통적으로 사용할 프로퍼티나 매서드를 프로토타입에 미리 구현해 두면 생성자 함수가 생성할 모든 인스턴스는 별도의 구분없이 상위(부모)객체인 프로토타입의 자산을 공유하여 사용할 수 있다.

 

__proto__ 접근자 프로퍼티

모든 객체는 __proto__ 접근자 프로퍼티를 통해 자신의 프로토타입에 접근할 수 있다.

// 모든 객체는 Object.prototype의 접근자 프로퍼티 __proto__를 상속받아 사용할 수 있다.
console.log({}.__proto__ === Object.prototype); // true

 

클래스와 인스턴스, 그리고 프로토타입

class Human{
  constructor(name){
    this.name = name;
  }

  sleep () {
    console.log(`${this.name}는 자는 중입니다.`)
  }
}

let steve = new Human('steve');
steve.sleep();			// 'steve는 자는 중입니다.'

Human.prototype.constructor === Human;		// true
Human.prototype === steve.__proto__;		// true
Human.prototype.sleep === steve.sleep;		// true

 

클래스(Human)를 통해 인스턴스(steve)를 만들면, 만들어진 인스턴스(steve)는 Human 프로토타입 체인의 일원이 된다. 따라서 만들어진 인스턴스 steve는 Human.prototype의 메서드인 .sleep을 상속받아 사용할 수 있다.

출처 : 코드스테이츠

 

프로토타입 체인?

Javascript는 객체의 프로퍼티에 접근하려고 할 때 해당 객체에 접근하려는 프로퍼티가 없다면 자신의 부모 역할을 하는 프로토타입의 프로퍼티를 순차적으로 검색한다. 이를 프로토타입 체인이라고 한다. 

 프로토타입 체인의 최상위에 위치하는 객체는 언제나 Object.prototype이다.(체인의 종점)

 프로토타입 체인은 상속과 프로퍼티 검색을 위한 매커니즘이라고 할 수 있다.

 

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

console.log(div.__proto__);			
console.log(div.__proto__.__proto__);		
console.log(div.__proto__.__proto__.__proto__);
console.log(div.__proto__.__proto__.__proto__.__proto__);
console.log(div.__proto__.__proto__.__proto__.__proto__.__proto__);
console.log(div.__proto__.__proto__.__proto__.__proto__.__proto__.__proto__);
// 순서대로
// HTMLDivElement	HTMLElement	Element	Node	EventTarget	Object

빌트인 메서드의 사용

우리가 사용하는 Javascript 기본 내장 메서드는 이러한 프로토타입 체인을 통하여 사용하는 것이다.

let arr = [1, 10, 15, 3, 11]

arr.sort((a,b) => a-b);

console.dir(arr);

arr.__proto__ === Array.prototype		// true

arr의 프로토타입 Array

arr 에는 sort라는 메서드가 없지만, 프로토타입 체인을 따라 올라가 Array.prototype 객체에 있는 sort 메서드를 사용할 수 있다.