자바스크립트 패턴 — 3.4 객체 프로토타입과 프로토타입 상속
5분 읽기
1. 기본 객체 프로토타입
자바스크립트의 거의 모든 객체는 Object.prototype을 포함하고 있습니다.
var chimp = {
hasThumbs : true,
swing : function () {
return '나무 꼭대기에 대롱대롱 매달려 있네요';
}
}위와 같이 2가지 속성을 객체 내에 추가하더라도, 실제로는 프로토타입이 하나 더 추가됩니다.
![]()
그렇기 때문에 해당 객체에 직접 포함하지 않은 chimp.toString()을 실행해도 에러가 발생하지 않고 [Object Object]라고 출력됩니다. 기본 Object.prototype에 포함된 속성이기 때문입니다.
2. 프로토타입 상속과 체인
객체 생성 시 기본적으로 만들어지는 프로토타입을 활용하면 흥미로운 동작이 가능합니다.
var ape = {
hasThumbs : true,
hasTail: false,
swing : function () {
return '매달리기';
}
}
var chimp = Object.create(ape);
var bonobo = Object.create(ape);
bonobo.habitat = '중앙 아프리카';
console.log(ape) // --- (1)
console.log(chimp) // --- (2)
console.log(bonobo) // --- (3)Object.create()는 지정된 프로토타입 객체 및 속성을 갖는 신규 객체를 생성하는 메서드입니다. chimp와 bonobo는 ape의 정보를 갖고 신규 객체를 생성하게 됩니다.
![]()
여기서 2가지를 알 수 있습니다.
Object.create()는 지정된 객체의 프로토타입과 속성을 새로 생성되는 객체의 프로토타입에 저장하여 생성합니다. 일반적인 객체처럼 바로 하단에 property가 추가되는 것이 아닙니다.console.log에서 보여주는 것은 해당 객체의 고유한 프로퍼티 속성뿐이며, 공유하고 있는 정보는 보여주지 않습니다.
ape에서 공유되어 사용된다는 사실은 아래에서 확인할 수 있습니다.
var ape = {
hasThumbs : true,
hasTail: false,
swing : function () {
return '매달리기';
}
}
var chimp = Object.create(ape);
var bonobo = Object.create(ape);
bonobo.habitat = '중앙 아프리카';
console.log(ape.hasThumbs) // true
console.log(chimp.hasThumbs) // true
console.log(bonobo.hasThumbs) // true
ape.hasThumbs = false
console.log(ape.hasThumbs) // false
console.log(chimp.hasThumbs) // false
console.log(bonobo.hasThumbs) // false
chimp.__proto__.hasThumbs = true
console.log(ape.hasThumbs) // true
console.log(chimp.hasThumbs) // true
console.log(bonobo.hasThumbs) // true여기서 추가적으로, __proto__에서 찾지 않고 chimp.hasThumbs로 직접 값을 지정하면 어떻게 될지 확인해보았습니다.
var ape = {
hasThumbs : true,
hasTail: false,
swing : function () {
return '매달리기';
}
}
var chimp = Object.create(ape);
var bonobo = Object.create(ape);
chimp.hasThumbs = false
console.log(ape.hasThumbs) // --- (1)
console.log(chimp.hasThumbs) // --- (2)
console.log(bonobo.hasThumbs) // --- (3)
console.log(chimp) // --- (4)![]()
여기서 알 수 있는 사실은, 자바스크립트에서 property 값은 다음과 같은 순서로 탐색된다는 것입니다.
- 해당 객체의 고유 프로퍼티명에 동일한 이름이 존재하는지 탐색 (있을 시 해당 값 반환하고 종료)
Object.prototype객체에 동일한 이름의 프로퍼티가 있는지 탐색 (있을 시 해당 값 반환, 없을 경우undefined반환)
결과적으로, 객체의 정보를 공유해서 쓰기에는 프로토타입 체인을 활용하는 것이 유용합니다. 다만 연결이 너무 복잡해질 경우 어디서 연결된 것인지 확인하기 어려우니 주의해서 사용하는 것이 좋습니다.