function Person(name, first, second){
this.name = name;
this.first = first;
this.second = second;
}
Person.prototype.sum = function(){
return this.first + this.second;
}
function PersonPlus(name, first, second, third){
Person.call(this, name, first, second);
this.third = third;
}
PersonPlus.prototype.avg = function(){
return (this.first+this.second+this.third)/3;
}
const kim = new PersonPlus('kim', 10, 20, 30);
console.log(kim.sum()); //error
console.log(kim.avg());
위 코드에서는 sum()
이라는 함수가 상속되지 않아 에러가 나는데, 그 이유는 아래 그림에서 찾아볼 수 있다.
이에 에러가 발생하지 않도록 하기 위해서는 아래 그림과 같이 PersonPlus' prototype
이 Person's prototype
의 sum()
함수를 참조할 수 있도록 바꾸어 주면 된다.
function Person(name, first, second){
this.name = name;
this.first = first;
this.second = second;
}
Person.prototype.sum = function(){
return this.first + this.second;
}
function PersonPlus(name, first, second, third){
Person.call(this, name, first, second);
this.third = third;
}
PersonPlus.prototype.__proto__ = Person.prototype;
PersonPlus.prototype.avg = function(){
return (this.first+this.second+this.third)/3;
}
const kim = new PersonPlus('kim', 10, 20, 30);
console.log(kim.sum()); //30
console.log(kim.avg()); //20
작동은 되나 이는 표준이 아니다!
function Person(name, first, second){
this.name = name;
this.first = first;
this.second = second;
}
Person.prototype.sum = function(){
return this.first + this.second;
}
function PersonPlus(name, first, second, third){
Person.call(this, name, first, second);
this.third = third;
}
// PersonPlus.prototype.__proto__ = Person.prototype;
PersonPlus.prototype = Object.create(Person.prototype);
PersonPlus.prototype.avg = function(){
return (this.first+this.second+this.third)/3;
}
const kim = new PersonPlus('kim', 10, 20, 30);
console.log(kim.sum()); //30
console.log(kim.avg()); //20
PersonPlus.prototype = Object.create(Person.prototype);
는, Person.prototype
의 객체를 __proto__
로 하는 새로운 객체를 만들라는 명령어이다.
function Person(name, first, second){
this.name = name;
this.first = first;
this.second = second;
}
Person.prototype.sum = function(){
return this.first + this.second;
}
function PersonPlus(name, first, second, third){
Person.call(this, name, first, second);
this.third = third;
}
// PersonPlus.prototype.__proto__ = Person.prototype;
PersonPlus.prototype = Object.create(Person.prototype);
PersonPlus.prototype.constructor = PersonPlus;
PersonPlus.prototype.avg = function(){
return (this.first+this.second+this.third)/3;
}
const kim = new PersonPlus('kim', 10, 20, 30);
console.log(kim.sum());
console.log(kim.avg());
console.log(kim.constructor);//[Function: PersonPlus]
PersonPlus.prototype.constructor = PersonPlus;
를 통해 부모객체를 바꿔주었다.