prototype chaining
개념
- 해당 객체에 property가 없을 경우, prototype에서 이를 탐색 & 반복(proto의 proto...)
const func1 = function() {
this.a = 10;
this.b = 20;
}
const obj1 = new func1();
func1.prototype.b = 21;
func1.prototype.c = 30;
console.log(obj1.a);
console.log(obj1.b);
console.log(obj1.c);
주의점
- proto의 depth가 많을 경우, 많은 chaining이 발생
- hasOwnProperty 메서드를 통해 방지 필요
if (obj1.hasOwnProperty()) {
console.log(obj1.c);
}
prototype 활용
function Person(name, age) {
this.name = name;
this.age = age;
}
Person.prototype = {
showInformation: function() {
console.log(`${this.name}의 나이는 ${this.age}입니다.`);
}
};
const kim = new Person('kim', 30);
const cu = new Person('cu', 28);
kim.showInformation();
cu.showInformation();
기타 : 상속
const a = {v: 1};
const b = Object.create(a);
const c = Object.create(b);
console.log(b.v);
console.log(c.v);