prototype
객체간의 상속을 구현하는 개념
function MakeFunc(name) {
this.name = name; // this는 생성될 객체를 가르킨다.
}
MakeFunc.prototype.greeting = function () { console.log(`hello ${this.name}`) };
const newFunc = new MakeFunc("Kim");
위 코드를 전제로 프로토타입을 한번 알아보자.
생성자 함수 MakeFunc을 만든다. (화살표 함수는 this 바인딩이 없다.). 생성자 함수엔 prototype 이라는 객체가 기본적으로 내장되어 있다. 이 prototype 객체에 greeting 메서드를 추가했다. 그런데 prototype 객체에 내가 추가하지 않은 constructor라는 프로퍼티가 있다.
constructor는 자신이 속한 prototype 객체를 가지고 있는 생성자 함수를 참조하고 있다.
MakeFunc 생성자 함수로 newFunc 객체를 만든 후, 내부를 보자. 생성자 함수의 this 바인딩으로 만든 값 말고도 [[Prototype]] 이라는 내부 슬롯이 있다.
__proto__ 는 [[Prototype]] 내부 슬롯을 참조하는 접근자이다. newFunc의 프로토타입은 MakeFunc의 prototype 객체를 참조하고 있다는걸 알 수 있다.
이렇게 newFunc에서 직접 정의하지 않은 greeting 메서드를 프로토타입을 통해 사용할 수 있는데, 이를 "프로토타입 체이닝" 이라고 한다.
'JavaScript' 카테고리의 다른 글
IntersectionObserver (0) | 2024.04.18 |
---|---|
FileReader (0) | 2024.03.23 |
Promise (0) | 2024.02.14 |
async/await (0) | 2024.02.09 |
axios (0) | 2024.01.19 |