
책 정보
이 글의 목적 및 대상 독자
new 키워드로 생성된 객체. 내부 슬롯 [[Prototype]]을 통해 constructor.prototype과 연결됨.function Person(name) {
this.name = name;
}
Person.prototype.greet = function() {
console.log(`Hello, ${this.name}`);
};
const alice = new Person('Alice');
alice.greet(); // Hello, Alice
💡 Tip
alice.__proto__ === Person.prototype이고,
Person.prototype.constructor === Person입니다.
function Foo() {}
Foo.prototype = {
bar() { return 'bar'; }
};
console.log(Foo.prototype.constructor === Foo); // false
// 올바르게 유지하려면
Foo.prototype = {
constructor: Foo,
bar() { return 'bar'; }
};
alice.greet = function() {
console.log('Hi there!');
};
alice.greet(); // Hi there!
[[Prototype]]을 따라 계속 검색Object.prototype, 그 이후 null이 되어 탐색 종료alice.__proto__
↳ Person.prototype
↳ Object.prototype
↳ null
hasOwnProperty, isPrototypeOf 등 Object.prototype 메서드는 프로토타입 체인의 중간에서 호출해도 동작Object.create(null)로 생성한 객체는 체인이 끊겨 있음const dict = Object.create(null);
console.log(dict.hasOwnProperty); // undefined
Object.create()를 두 번 이상 적용해 다단 체인을 구성 가능const base = { a: 1 };
const mid = Object.create(base, { b: { value: 2, enumerable: true } });
const top = Object.create(mid, { c: { value: 3, enumerable: true } });
console.log(top.a, top.b, top.c); // 1 2 3
[[Prototype]] 관계를 이해Object.create(null) 예외 등 주요 포인트 숙지