본문 바로가기

프론트지식

자바스크립트 Prototype 이해하기

const numbers = [4, 2, 1];
numbers.sort();
console.log(numbers);	// [1, 2, 4]

Q. array 자료형에 .sort()를 붙일 수 있는 이유가 뭘까?

 

Array.prototype 이라는 부모로부터 sort라는 메서드를 물려받았기 때문 = 상속

자바스크립트에서 상속을 어떻게 구현하는지 살펴보자.

 

Prototype의 뜻은? "원형"

자바, 파이썬 등 클래스 기반 언어는 클래스를 정의하고 -> 객체를 생성한다.

자바스크립트는 클래스가 없는 대신 프로토타입이 있다. (ES6에서 프로토타입을 class로 쓸 수 있게 문법 추가됨)

자바스크립트프로토타입으로 클래스의 상속을 흉내낸다.

(상속: 자식 클래스에서 부모 클래스의 모든 프로퍼티와 메서드를 사용할 수 있는 것)

자바스크립트의 모든 객체는 그들의 프로토타입 안에 부모의 프로퍼티와 메서드를 상속받는다.

const student = {
  name: 'Noah',
  score: 100
};

// student에는 hasOwnProperty 메소드가 없지만 아래 구문은 동작한다.
console.log(student.hasOwnProperty('name')); // true

console.dir(student);

student는 Object라는 부모가 가진 모든 프로퍼티와 메서드를 [[Prototype]] 안에 담고있다.

 

ECMAScript spec상의 [[Prototype]] 설명

  • 모든 객체는 [[Prototype]]이라는 인터널 슬롯(internal slot)를 가진다.
  • 객체의 입장에서 자신의 부모 역할을 하는 Prototype 객체를 가리킨다.
  • [[Prototype]]의 값은 객체(프로퍼티와 메서드가 담겨있음) 또는 null(부모가 더 이상 없을 때)이다.

 

자식 객체의 __proto__ 프로퍼티는 자신의 [[Prototype]] 객체를 가리킨다.

부모의 모든 프로퍼티와 메서드는 부모.prototype이라는 객체에 담겨있다.

자식.__proto__ === 부모.prototype
console.log(student.__proto__ === Object.prototype); 	// true

 

아래 사이트에서 animal과 rabbit의 관계를 이해해보자.

https://ko.javascript.info/prototype-inheritance

 

프로토타입 상속

 

ko.javascript.info

 

Prototype의 작동원리

객체는 언제나 함수로 생성된다.

우리가 자주 쓰는 객체 리터럴 방식도 결국 함수로 생성된다.

const obj = {};
const arr = [];
// 위 코드와 아래 코드는 동일하다.
const obj = new Object();
const arr = new Array();

 

new 연산자를 사용해 생성한 객체는 생성자의 프로퍼티와 메서드(prototype) 상속받는다.

const obj = new Object(); 	// 이 객체의 프로토타입은 Object.prototype 이다.
const arr = new Array();  	// 이 객체의 프로토타입은 Array.prototype 이다.
const date = new Date();  	// 이 객체의 프로토타입은 Date.prototype 이다.

 

 

생성자 함수를 사용하여 객체를 생성해도 마찬가지이다.

function Student(name, score) {
    this.name = name;
    this.score = score;
}

const student1 = new Student('Noah', 100);

student1의 프로토타입은 무엇일까?

console.log(student1.__proto__ === Student.prototype);	// true

 

Student.prototype에 새로운 값을 추가할 수도 있다.

Student.prototype.sayHello = function() {
    console.log('hello');
}

 

프로토타입 체인