prototype은 객체의 청사진을 만들때 쓰는 원형객체 (original form)이다
Javascript는 prototype기반의 언어로서 prototype을 이용하여 OOP를 모방하다가 최근 ES6에서 class 키워드가 등장하여 이를 이용해 모방하였지만 어디까지나 모방이라 class키워드가 있다고 class기반 언어와 같이 상속기능이 존재하지않는다
모든 function에는 prototype이 있다
prototype 객체에 property나 method를 정의할수있다 (original form 이기때문)
(instantaion) function man(name){ this.name = name } let 박지훈 = new Human
man을 blueprint로 박지훈이라는 객체를 instantaion했을때
박지훈.__proto__ === man.prototype //true
박지훈과 man의 prototype의 관계성을 'prototype chain' 이라고 부른다
➕ 가끔 method를 정의하지않았는데 사용가능한 이유
모든 객체들은 끝엔 Object(자바스크립트의 대표객체라고 할수있는)라는 원형객체에 속해있다
결국 모든 객체들은 이 Object란 객체를 상속받았기때문에
정의해주지않은 method를 사용할수있는것도
Object의 메소드를 상속받아 사용할수있는 것 이다
프로토타입은 할당이 가능하여
특정한 클래스에 작동시키고싶은 프로토타입을 넣으면
해당 프로토타입처럼 작동한다
부모클래스의 메소드를 상속받고 추가적으로 메소드를 더 만들고싶을경우
자식.prototype = 부모.prototype 할당시킬경우
두 주소는 같아 한마디로 부모prototype에도 메소드가 추가되어버린다
이 경우를 방지하기위해선 부모prototype을 카피해서 할당시켜주려고하는데
자식클래스명.prototype = Object.create(부모클래스명.prototype) //그 후 new 키워드로 instantaion let 자식1 = new 자식클래스명 자식클래스명.prototype.메소드명 = function() { 메소드내용 } //메소드 추가 자식1.메소드() //메소드 실행
Object.create() 는 첫번째 인자로 들어가는 prototype객체를 바탕으로 새로운 ?prototype객체를 생성하는 메서드이다 -> .slice()와 유사
자식클래스.proto.constructor 키워드로 확인해보면 아직 부모의 constructor(생성자함수)를 바라보고있다
자식클래스의 constructor를 이어주면된다
constructor : class가 insatance화 할때 최초로 실행되는 함수
자식클래스명.prototype.constructor = 자식클래스명
new 키워드로 instance를 만들때 this는 instance가 된다
하지만 자식클래스의 context가 전달이 되지않는데
한마디로 부모 클래스의 this가 연결이 되어있지않아 undefined가 나온다
-> 자식클래스로 생성한 instance로 부모클래스에게 상속받은 메소드 실행시 해당 메소드는 undefined
let 자식클래스명 = function(){ 부모클래스명.call(this, argument) // 부모클래스명.apply(this, arguments) }
let 부모 = function(name) { this.name = name; } var 자식 = function(name) { 부모.call(this, name); // 문제점3. 자식클래스의 context 전달 }; 자식.prototype = Object.create(부모.prototype); // 문제점1. 부모 참조끊기 자식.prototype.constructor = 자식; // 문제점2. constructor 연결 자식.prototype.추가메소드 = function() {}; // 메소드 추가하기
class 부모 { constructor(name){ this.name = name } sleep() { } } ---------------------------------- class 자식 extends 부모 { constructor(name){ super(name) } 추가메소드(){ // 상속받을 메소드는 생략 } }