javascript 상속 (prototype / class)

2019. 3. 21. 18:33·WEB/JavaScript

1. prototype


//생성자를 정의한다.

var Human = function(name) {

this.name =name;

}


//생성자의 prototype에  sleep이라는 함수를 할당한다.

Human.prototype.sleep = function( ) { };


var steve = new Human('steve');


function에는 기본적으로 prototype에 constructor가 생성된다.

__proto__는 생성된 인스턴스가 참조하고 있는 prototype을 뜻한다.

Human.prototype 으로 Human의 prototype에 접근이 가능하다.

Human.Prototype.constructor 는 Human이다.

-> new를 사용해서 만들 경우 생성자가 어떤 함수인지를 뜻한다.


var Human = function(name) {

this.name =name;

}


Human.prototype.sleep = function( ) { };


var steve = new Human('steve');



//Student 생성자를 정의

var Student = function(name) {


};


//Student의 prototype에 learn 함수를 정의

Student.prototype.learn = function ( ) { };


var john = new Student( 'john');


//learn함수는 실행 가능

john.learn();


//sleep은 Human생성자에 있는 함수이며, Student생성자에는 없기 때문에 err

john.sleep(); // type err , sleep is not a function 




Student에서 sleep함수를 사용하려면 ?

#1

john의 __protp__가 Human.prototype을 참조하게 만든다.

하지만 이 방법은 결코 좋은 방법이 아니기 때문에 사용하지 않는다.


#2

Student.prototype이 Human.prototype을 참조하게 한 후 learn 함수를 추가 시킨다

하지만 Human.prototype과 Student.prototype 모두 learn 함수를 가지기 때문에 이 방법도 베스트는 아니다.

객체를 참조하게 되면 같은 메모리를 바라보기 때문에 하나를 수정하게 되면 둘 모두에게 영향이 간다.


#3

Student.prototype에 Object.create를 사용해서 Human.prototype를 참조하는 새로운 객체를 만든다.

 -> Human의 prototype을 참조하기 때문에 Student.__proto__ 는 Human을 참조한다

그 후에 Student.prototype에 learn 함수를 추가해도 새로 생성된 객체이기 때문에 메모리 주소가 달라 Human.prototype에 learn 함수가 추가되지 않는다.



하지만 Human.prototype를 참조하고 있기 때문에 Student.prototype.constructor가 Human이라는 값을 가지고 있다.

-> function을 정의 할 때 prototype에 constructor가 생성되기 때문에

따라서 Object.create 후에 Student.prototype.constructor = Student로 재정의 해줘야한다.


마지막으로 sleep함수는 Student.__proto__가 참조하고 있는 Human 생성자 안에 있기 때문에 Student 생성자를 new키워드를 사용하여 생성 후에

sleep 함수를 사용하기 위해서는 call을 사용하여 john을 this로 하는 Human의 sleep함수를 실행 할 수 있게

Student 안에 Human.call(this, name)을 작성한다



2. class

es6 문법으로 class 키워드를 사용해서 생성자를 만들 수 있다.

constructor안에 생성사의 정보를 입력한다.

super 키워드는 extends한 클래스의 함수를 사용할 수 있게 한다.

위에서 call한 것과 비슷하다고 보면 될거 같다.

'WEB > JavaScript' 카테고리의 다른 글

자바스크립트로 팝업창 구현  (0) 2019.07.08
JSON 이란  (1) 2019.03.31
es6문법 비구조화 할당  (0) 2019.03.07
es6 문법 const let var  (0) 2019.03.07
Javascript Event loop  (0) 2019.03.04
'WEB/JavaScript' 카테고리의 다른 글
  • 자바스크립트로 팝업창 구현
  • JSON 이란
  • es6문법 비구조화 할당
  • es6 문법 const let var
vitnal
vitnal
4년차 프론트엔드 개발자입니다. react를 사용하여 웹 서비스를 개발한 경험이 있습니다. github: https://github.com/jch1223
  • vitnal
    vitnal 아카이브
    vitnal
  • 전체
    오늘
    어제
    • 분류 전체보기 (146)
      • AI (1)
      • WEB (76)
        • React (21)
        • Nextjs (17)
        • JavaScript (16)
        • React Native (5)
        • HTML & CSS (7)
      • CS (3)
      • Git (15)
      • Dev Tools (23)
      • Deploy (12)
      • Tech Memo (8)
      • Retrospect (7)
  • 반응형
  • hELLO· Designed By정상우.v4.10.5
vitnal
javascript 상속 (prototype / class)
상단으로

티스토리툴바