자바스크립트는 프로토타입 기반 언어인데 이거에 대해 한 번도 글을 쓰지 않았다니~!
참고
자바스크립트 객체는
[[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 상속
.앞에 있는 메서드를 호출한 객체를 가르킴const food = {
eatable: true,
printThis: function () {
console.log(this.color)
}
}
const banana = {
color: 'yellow',
__proto__: food
}
banana.printThis() // 'yellow' 출력
프로토타입 정리 끝 ~!