Inheritance Patterns

이재진·2020년 10월 29일
0

Inheritance Patterns

목록 보기
3/3
post-thumbnail

Inheritance Patterns

공통으로 가진 기능, 중복되는 것들이 보인다.
동물도 이름이 있고 사람도 이름이 있다. 중복은 개선 가능하다면 바꿀수 있어야 한다.

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이 상위의 개념. 하위 계층들이 상위의 개념을 끌어와서 써야 함.

  1. 8번째 줄 this.language = language;는 Human의 고유 한 것이기 때문에 가만히 둔다.
  2. 6번째 줄 Human 함수 내에 this.name = name을 지우고 Animal을 일단 쓴다.
  3. Animal이라는 변수가 뜻하는 것은 생성자 함수이다. 함수에는 call이라는 메소드가 있다. call은 this 바인딩 할 때 쓴다. Animal.call(this) 이 때 this를 this로 쓴다.
  4. Human이라는 함수의 this를 판별하려면 실행된 부분을 봐야 한다. Human이라는 함수는 12번째 줄에서 new Human으로 실행되었다. 그렇다면 그 this는 Human인스턴스이다. Animal.call(this)의 this는 Animal이란 함수를 실행하는데 Human인스턴스로 설정해서 실행했다고 할 수 있다.
  5. 6번째 줄이 실행되면 첫번째 줄 Animal이라는 함수가 실행된다. 그런데 실행할 첫번째 줄 Animal이라는 함수도 안에 this를 가지고 있다. Animal이라는 함수의 this를 판별하려면 방금 6번째 줄에서 animal을 call로 실행시킨 것을 본다.
  6. call해서 Human인스턴스(this)로 지정해서 실행시켰다. 그래서 Animal함수 내 의 this는 Human인스턴스로 지정되고 name이라는 속성을 만들게 된다. 또 인자가 있기에 Animal.call(this, name)으로 인자를 넘겨 줄 수 있다.
    앞으로 공통적인 것을 바꿀 때 상단계층의 것만 바꾸면 하위의 공통 내용을 바꿀 수 있게 된다.

Object.create에 대해서

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 메소드를 사용해도 답이 나온다.
상위,하위가 동등해진다는 것을 의미하고 상위에는 없어도 되는 행위를 사용할 수 있게 되어 오작동이 일어난다.

profile
개발블로그

0개의 댓글