[Javascript] Prototype

한별·2023년 9월 30일

Javascript

목록 보기
5/25

Prototype

자바스크립트에서 객체를 상속하기 위해 사용하는 것

자바스크립트에는 클래스가 없어서 상속 기능도 없다.
하지만, 프로토타입을 이용하여 상속을 흉내낼 수 있다.

Function & new

함수와 new를 이용하여 JS에서 클래스와 유사하게 사용할 수 있다.

function Person() {
	this.eyes = 2;
  	this.nose = 1;
}

var kim = new Person();
var park = new Person();

console.log(kim.eyes); // 2
console.log(park.nose); // 1

다음 코드의 문제점은 객체마다 eyes, nose 메모리가 할당되므로 객체를 100개 만들면 200개의 변수가 메모리에 할당된다는 문제가 있다. → 메모리 낭비

Prototype

function Person() {
}

Person.prototype.eyes = 2;
Person.prototype.nose = 1;

var kim = new Person();
var park = new Person();

console.log(kim.eyes); // 2
console.log(park.nose); // 1

프로토타입을 사용하면 eyes와 nose를 빈 공간에 넣어놓고 kim과 park가 공유해서 사용하기 때문에 문제가 해결된다.

⚠️ 사실 일반적인 방식으로는 속성은 생성자에서, 메소드는 프로토타입에서 정의한다.

Prototype = Prototype Object + Prototype Link

Prototype Object

함수를 정의하면 함수만 생성되는 것이 아니라 Prototype Object도 함께 생성된 후 연결된다.

Person Prototype Object는 Person 함수의 상위 객체이고
Person Prototype Object의 함수는 Person 함수에서 자유롭게 사용 가능하다.

코드

function Person() {}
Person.prototype.eyes = 2;
Person.prototype.nose = 1;
var kim  = new Person();
var park = new Person():

__proto__는 Prototype Object를 가리킨다.

kim.__proto__의 경우, Person Prototype Object를 가리키고 있는 것이다.
이것이 kim 함수에는 eyes 속성이 없지만 kim.eyes의 값이 2인 이유이다.

kim 객체가 eyes를 직접 가지고 있지 않으므로 eyes를 찾을 때까지 상위 프로토타입을 탐색한다. 만약 최상위 프로토타입인 Object Prototype Object까지 탐색했는데도 속성이 없는 경우 undefined를 리턴한다.

프로토타입 체인

이러한 이유로 우리는 모든 객체에서 Object Prototype Object의 속성인 toString 함수를 사용할 수 있는 것이다.

참고 자료

[bluesh55][Javascript] 프로토타입 이해하기

profile
글 잘 쓰고 싶어요

0개의 댓글