본문 바로가기

JS&TS Essential

함수의 prototype

https://code-mania.tistory.com/135

 

Prototype

JS는 프로토타입 기반언어라고 불리기도 한다. 이 프로토타입이란 무엇인지 어떤 메카니즘이 있는지 알아보자!! [[Prototype]] 다들 객체를 console에 찍어본 경험이 한 번 정도는 있을 것이다. 이 때

code-mania.tistory.com

 

전 시간에 살펴본 Prototype은 모든 객체에 적용된다.
하지만 함수에는 조금 더 추가된 Prototype 메카니즘이 적용된다.


new Method()와 같이 함수 앞에 new 키워드를 사용하여 객체를 생성할 수 있다.

new 키워드에는 약간의 비밀이 숨겨져있다.

비밀을 이해하기 위해 먼저 함수의 prototype이라는 프로퍼티에 대해 알아보자!

우선 prototype은 함수에 정의된 일반 프로퍼티이다.

(이전 시간에 배웠던 숨김 프로퍼티인 [[Prototype]]과는 다른 속성이다.)

prototype이 객체일 경우 new 연산자는 생성한 객체의 [[Prototype]]prototype을 연결해준다.

 

 

const instrument = {
    name: '악기',
    play() {
        console.log(`${this.name} 연주`)
    }
}

function Piano(kind) {
    this.kind = kind;
}
Piano.prototype = instrument;

let piano = new Piano('digital');
// piano.__proto__ = instrument;

console.log(piano);
piano.play();

 

 

즉, new를 사용하는 것은 생성된 객체의 __proto__에 함수의 prototype을 연결하는 것과 같다.

[[Prototype]]instrument로 지정되고 play()가 정상실행된다.

prototype속성은 new 연산자와 함께 사용될 때만 동작한다!

 

prototype과 constructor

만약 함수의 prototype을 직접 할당하지 않으면,

기본적으로 prototype은 자신을 constructor 프로퍼티로 가지는 객체를 가리키게 된다.

 

 

function Piano(kind) {
    this.kind = kind;
}
// 기본 prototype
// Piano.prototype = { constructor: Piano };

 

따라서 다음과 같이 객체를 생성할 수도 있다.

 

function Piano(kind) {
    this.kind = kind;
}
let piano = new Piano('digital');
let piano2 = new Piano.prototype.constructor('digital');

 

'JS&TS Essential' 카테고리의 다른 글

Prototype  (0) 2021.11.30
AJAX와 Axios 안에 있는 것  (0) 2021.10.23
JS와 event loop  (0) 2021.08.01