Object.prototype
JavaScript에서 거의 모든 객체는 Object의 인스턴스입니다. 일반적인 객체는 Object.prototype 에서 속성과 메서드를 상속받으며, 그 중 일부는 (오버라이드 등으로 인해) 숨겨질 수 있습니다. 그러나, 의도적으로 Object를 생성할 때 (Object.create(null) 처럼) 이를 피할 수도 있고, Object.setPrototypeOf 등을 통해 나중에 무효화할 수도 있습니다.
Object 프로토타입에 가하는 변경은 프로토타입 체인을 통해, 더 아래쪽 체인에서 덮어 쓴 경우가 아니라면 모든 객체에서 관측할 수 있습니다. 이는 객체를 확장하거나 행동을 바꿀 수 있는 매우 강력하면서도 위험한 방법을 제공합니다. --- MDN 설명
// MDN 예시 코드
var Person = function() { // Person객체 생성
this.canTalk = true;
};
Person.prototype.greet = function() {
if (this.canTalk) {
console.log('Hi, I am ' + this.name);
}
};
var Employee = function(name, title) {
Person.call(this); // Person객체의 this를 지칭
this.name = name;
this.title = title;
};
Employee.prototype = Object.create(Person.prototype); // Person객체를 참조
Employee.prototype.constructor = Employee; // 자신을 지칭
Employee.prototype.greet = function() {
if (this.canTalk) {
console.log('Hi, I am ' + this.name + ', the ' + this.title);
}
};
var kim = new Employee('kim', student);
[설명]Person객체를 생성시 Person.prototype이 생성된다. 그리고 Person.prototype.constructor는 Person을 가리킨다. 그리고 Employee.prototype이 Person.prototype을 참조하게 한다면, 그의 constructor 또한 Person을 지칭하므로 자신을 지칭할 수 있도록 다시 Employee로 변경해준다. 그리고 새롭게 생성된 kim객체는 Employee.prototype를 가리킨다. 따라서 kim.proto 는 Employee.prototype를 가리킨다.
조금 보충 할 것!