[javascript] 객체 할당에서 프로토타입 체인의 영향.
// 부모 객체
var parent = {
name: "Parent",
greet: function() {
return "Hello, I am " + this.name;
}
};
// 자식 객체
var child = Object.create(parent);
child.name = "Child";
console.log(child.greet()); // "Hello, I am Child"
위 예제에서 child
객체는 parent
객체를 프로토타입으로 상속받았습니다. 이로 인해 child
객체는 parent
객체의 greet
메서드를 사용할 수 있게 되었습니다.
그러나 객체에 직접 속성을 할당할 때, 프로토타입 체인은 어떻게 작용할까요? 예를 들어, child
객체에 greet
메서드를 다시 할당하면, 이 메서드는 child
객체에 직접 할당되며 프로토타입 체인의 영향을 받지 않습니다.
child.greet = function() {
return "Hey there!";
};
console.log(child.greet()); // "Hey there!"
따라서, child
객체에서 greet
메서드를 호출하면 프로토타입의 greet
메서드가 아닌 직접 할당한 greet
메서드가 호출됩니다.
프로토타입 체인은 객체를 상속할 때 유용한데, 객체에 직접 속성을 할당할 경우에는 주의가 필요합니다.