공통으로 가진 기능, 중복되는 것들이 보인다.
동물도 이름이 있고 사람도 이름이 있다. 중복은 개선 가능하다면 바꿀수 있어야 한다.
1.function Animal (name) {
2. this.name = name;
3.}
4.
5.function Human (name) {
6. Animal.call(this, name);
7. //this.name = name;(중복되는 부분)
8. this.language = language;
9.}
10.
11.var dog = new Animal("chiwawa");
12.var jin = new Human("jin", "korean");
위 코드를 통해서 이해해보자면
this.name = name;이 부분이 중복이다. 중복되는 것을 뺀다.
Animal이 상위의 개념. 하위 계층들이 상위의 개념을 끌어와서 써야 함.
function Human(name) {
this.name = name;
}
//function Student(name){
// this.name = name
//}
function Student(name) {
Human.apply(this, arguments) // Human 과 Student 의 this를 같이 공유, 하나의 context를 공유
}
Human.prototype.sleep = function () {
console.log("sleep");
};
//Student.prototype.sleep = function () { //중복
// console.log("sleep");
//};
Student.prototype = Object.create(Human.prototype) //복사
Student.prototype.constructor = Student; //student의 부인의 남편은 student로 다시 해줌.
위 코드를 통해서 이해해보자면
Human이 더 상위 개념이므로 하위인 Student의 속성을 뺀다.
함수를 하나 만들어줄 때는 자동적으로 prototype 이라는 객체가 생긴다.
Human 과 Student 함수를 만들어줄 때, Human.prototype과 Student.prototype 객체가 생긴다.
Student.prototype -> Human.prototype -> Object.prototype 이 순서로 만들어줘야 한다.
그래서 Human.prototype의 속성을 똑같이 가진 새로운 프로토타입 객체를 Object.create를 통해서 만든다.
Object.create라는 메소드는 빈 객체를 만들어서 반환해준다.
위 두번째 사진을 보면 jin에게는 없는 hello라는 속성이 생겼고 1이 나왔다. 이 말은 jin의 prototype이 obj.prototype이 되었다는 것을 의미한다. Object.create()안의 인자를 넣어주면은 반환되는 빈 객체의 프로토타입이 ()의 인자로 된다. 위 예시로 보면 obj를 프로토타입으로 갖는 빈 객체를 만들어주는 것.
Object.create(Human.prototype)는 빈객체를 반환해준다. 그 빈 객체의 prototype은 Human이 된다.
만들어진 그 빈 객체에 Human을 넣어주게 되면 Student.prototype에 할당해주었기 때문에 Student는 Human의 상속을 받게 된 것.
추가적으로 Object.create를 통해서 상속을 받게 되면 자식 객체의 프로토타입 변화가 부모 객체의 프로토타입에 영향을 주지 않으며, 부모 객체의 프로토타입 변동은 자식 객체에 적용된다.
마지막으로 Student.prototype.constructor 를 Student로 다시 해줘야 하는 작업이 필요하다.
최종적으로 Student.prototype -> Human.prototype -> Object.prototype 이 순서의 프로토타입 체인이 이루어진다.
function Person (name) {
this.name = name;
}
function Student (name) {
this.name = name;
}
//Student.prototype = Object.create(Person.prototype);
Student.prototype = Person.prototype;// 주소값이 같아 짐.
Student.prototype.hello = function () {
console.log("hello world")
}
const boo = new Person()
boo.hello() //"hello world"
Student.prototype = Person.prototype 이 상황에서는 주소값이 같아져서 상위의 Person함수의 인스턴스가 하위의 hello 메소드를 사용해도 답이 나온다.
상위,하위가 동등해진다는 것을 의미하고 상위에는 없어도 되는 행위를 사용할 수 있게 되어 오작동이 일어난다.