프로토타입 상속

·2024년 6월 11일

자바스크립트

목록 보기
7/21

constructor 가 뭐야 : 너 출신 생성자 함수가 어디야
prototype 은 뭐야 : 너 뭐 공유받았어 너 원형이 뭐야!

함수의 메서드

call : this를 전달 + 인수를 개별로 받는다. 함수 바로 실행

apply : this를 전달 + 인수를 배열로 받는다. 함수 바로 실행

bind : call처럼 전달 + 함수 나중에 실행 (const a = ().bind())


프로토타입 이해할 때 썼던 gpt

생성자 함수인 Rabbit의 프로토타입을 명시적으로 지정하지 않았을 때, Rabbit의 프로토타입은 기본적으로 빈 객체이며, 이 객체는 자동으로 Object.prototype을 프로토타입으로 갖습니다.

기본 상태의 프로토타입

생성자 함수를 정의하면 JavaScript는 자동으로 prototype 속성을 빈 객체로 설정합니다. 이 기본 프로토타입 객체는 constructor 속성을 가지고 있으며, 이는 생성자 함수 자신을 가리킵니다.

예시

function Rabbit(name) {
  this.name = name;
}

const bunny = new Rabbit('Bunny');

console.log(bunny.name); // "Bunny"
console.log(bunny.__proto__ === Rabbit.prototype); // true
console.log(Rabbit.prototype); // 기본적으로는 빈 객체: {}
console.log(Rabbit.prototype.constructor === Rabbit); // true
console.log(Object.getPrototypeOf(bunny) === Rabbit.prototype); // true

위의 코드에서:

  1. Rabbit 생성자 함수가 정의됩니다.
  2. Rabbit.prototype은 자동으로 빈 객체로 설정됩니다.
  3. Rabbit.prototype.constructorRabbit을 가리킵니다.
  4. bunny 객체의 프로토타입(__proto__)은 Rabbit.prototype입니다.

프로토타입 체인

Rabbit의 프로토타입 체인은 다음과 같습니다:

Rabbit.prototype -> Object.prototype -> null

다이어그램으로 표현

bunny -> __proto__ -> Rabbit.prototype -> __proto__ -> Object.prototype -> null
  • bunny.__proto__Rabbit.prototype을 가리킵니다.
  • Rabbit.prototype.__proto__Object.prototype을 가리킵니다.
  • Object.prototype.__proto__null을 가리키며, 프로토타입 체인의 끝을 나타냅니다.

요약

  • 생성자 함수의 프로토타입은 기본적으로 빈 객체로 설정됩니다.
  • 이 프로토타입 객체는 constructor 속성을 가지고 있으며, 이는 생성자 함수 자신을 가리킵니다.
  • 생성자 함수로 생성된 객체는 그 생성자 함수의 prototype 객체를 프로토타입으로 가집니다.
profile
'한 번 더!'의 가능성을 믿어! 오늘도 열심히 굴러가 보는 프론트엔드 개발자 😎

0개의 댓글