[프로토타입(prototype)]
JavaScript는 프로토타입(Prototype) 기반의 언어이며 프로토타입은 객체의 원형(origin)을 의미한다.
자바스크립트의 모든 객체는 하나 이상의 다른 객체로부터 상속을 받고, 이때 상속되는 정보를 제공하는 객체를 프로토타입이라고 한다.
➡️객체를 상속하기 위한 매커니즘이다.
class Human {
constructor(name, age) {
this.name = name;
this.age = age;
}
sleep() {
console.log(`${this.name}은 잠에 들었습니다`);
}
}
let kimcoding = new Human('김코딩', 30);
Human.prototype.constructor === Human; // true
Human.prototype === kimcoding.__proto__; // true
Human.prototype.sleep === kimcoding.sleep; // true
[.prototype]
.prototype은 클래스에서 프로토타입으로 접근할 때 사용한다.
(null) ➡️ Object ➡️ Object.prototype ➡️ Human ➡️ Human.prototype ➡️ new Human
[__prototype__]
__prototype__ 은 인스턴스에서 프로토타입에 접근할 때 사용한다.
steve ➡️ Human.__prototype__ ➡️ Human ➡️ Object.__prototype__ ➡️ Object ➡️ (null)
Human이라는 클래스와 인스턴스, 그리고 프로토타입의 관계
Array(배열) 클래스와 인스턴스, 그리고 프로토타입의 관계
⭐️ Array는 클래스.
배열은 Array 클래스의 인스턴스이며, Array.prototype에는 push, pop 등 다양한 메서드가 있다.
MDN에서 Array.prototype.push 라고 써 이유는 상속 때문이다.
'JavaScript' 카테고리의 다른 글
npm version update 하는 법 (0) | 2022.07.25 |
---|---|
JavaScript 프로토타입 체인 (0) | 2022.07.25 |
JavaScript 객체 지향 프로그래밍 (0) | 2022.07.22 |
JavaScript 클래스와 인스턴스 (0) | 2022.07.22 |
일급객체/고차함수 (0) | 2022.07.21 |