[JS] Prototype

조수현·2025년 6월 22일

서론

자바스크립트는 프로토타입 기반 언어인데 이거에 대해 한 번도 글을 쓰지 않았다니~!

참고

Prototype이란

자바스크립트 객체는 [[Prototype]]이라는 숨겨진 프로퍼티가 참조하는 객체, 대상을 프로토타입이라고 부름

__proto__

  • [[Prototype]]을 설정할 수 있음
  • [[Prototype]]의 getter, setter의 역할을 함
  • 최근에는 getPrototypeOf, setPrototypeOf를 사용함
const food = {
  eatable: true
}


//방법 1
const banana = {
  color: 'yellow',
  __proto__: food
}


//방법 2
const strawberry = {
  color: 'red '
}

strawberry.__proto__ = food

상속 프로퍼티

  • 객체에서 찾으려는 속성이 없다면 자동으로 프로토타입에서 찾음
  • 이 때 객체에는 없고 프로토타입에 있는 프로퍼티를 상속 프로퍼티라고 함
  • Object.keys()를 사용하면 객체의 프로퍼티만 반환
  • for(let prop in 객체)를 사용하면 객체와 프로토타입의 프로퍼티 반환
// 상속 프로퍼티
console.log(strawberry.eatable) // true 출력

console.log(Object.keys(strawberry)) // color만 출력
for(let props in strawberry) console.log(props) // color, eatable 출력

프로토타입 체이닝

  • 객체의 프로토타입의 대상 객체의 프로토타입도 객체에서 접근 가능하다
const food = {
  eatable: true
}

const banana = {
  color: 'yellow',
  __proto__: food
}

const shortBanana = {
  length: 'short',
  __proto__: banana
}

console.log(shortBanana.length)
console.log(shortBanana.color) // banana 상속
console.log(shortBanana.eatable) // banana의 프로토타입인 food 상속

this

  • 객체의 메서드는 프로토타입의 영향을 받지 않음
  • this는 .앞에 있는 메서드를 호출한 객체를 가르킴
const food = {
  eatable: true,
  printThis: function () {
  	console.log(this.color)
  }
}

const banana = {
  color: 'yellow',
  __proto__: food
}

banana.printThis() // 'yellow' 출력

마무리

프로토타입 정리 끝 ~!

profile
프론트엔드 개발 블로그

0개의 댓글