//상속할 개체 Person
const Person = function(name,age){
this.name = name;
this.age = age;
}
//Person의 prototype에 'greeting' 메소드 추가
Person.prototype.greeting = function(){
console.log(this.name, this.age);
}
//상속 받을 객체 Teacher
const Teacher = function(name,age,role){
Person.apply(this, arguments);
this.role = role;
}
- Person.apply(this, arguments) : Person의 생성자에 Teacher의 this와 arguments를 적용, new 키워드가 없으므로 객체를 생성하지않고, 생성자 함수만 실행되어서 Teacher안에 name, age속성을 추가한다.
- this.role = role : role은 Person의 매개변수안에 포함되어있지 않으므로, 따로 속성을 추가.
- 현재 Teacher.prototype.constructor === Teacher //true
- Teacher에서 Person의 greeting 메소드를 사용하지 못함
: Object.create는 객체를 만들되 생성자는 실행 X, new는 생성자를 실행
: 상속받는 객체의 prototype과 부모의 prototype를 연결시켜준다 => 그래야지 상속받은 객체에서 부모의 메소드를 사용할 수 있다.
Teacher.prototype = Object.create(Person.prototype);
- 따라서, greeting 메소드를 사용하기 위해, Teacher의 prototype에 Person의 Prototype를 연결한다.
: 생성자.prototype.constructor === 생성자 이므로, 상속받은 객체에서 Child.prototype.constructor = Child를 넣어줘서 에러를 해결해 줘야한다.
: 하지 않았을 경우, Child.prototype.constructor === Parent 상태이다.