191120(수) 3. Understanding Prototype Chain

RamiTae·2019년 11월 20일
0

TIL

목록 보기
15/17

[CODESTATES im16] Understanding Prototype Chain

1. 자바스크립트?

prototype기반의 언어.

ES5까지는 class가 없었음. > sudo-classical

ES6부터 calss 지원(하지만 그렇다고 해서 JS가 프로토타입 기반의 언어인 것은 변하지 않았음.)

2. prototype 상속

2-1. __proto__: 프로토타입을 확인할 수 있다.

function Human(name) {
    this.name = name;
}
let steve = new Human('steve');
steve.__proto__ === Human.prototype; //true

Q1. 아래 코드가 실행되는 이유는?

var Human = function(name) {
    this.name = name;
}
Human.prototype.sleep = function() {};

var steve = new Human('steve');
steve.toString(); // [object Object]

Human.__proto__에는 toString()이 없음. 하지만 Human의 기본형인 Object에는 toString()이 존재함. (모든 객체는 Object를 상속받음)

steve.__proto__.__proto__ === Object.__proto__; //true

2-2. JS에서 상속 구현하기

1) .__proto__.prototype대입: 상속이 아님

var Human = function(name) {
    this.name = name;
}
Human.prototype.sleep = function() {
    console.log('zzz');
}

var Student = function() {}
Student.prototype.learn = function() {
    console.log('배우는 중...');
}

var student1 = new Student();
student1.__proto__ = Human.prototype; //Error는 안생기지만 이렇게 쓰지 않는 것이 좋다.

__proto__프로퍼티는 참조의 용도로만 사용해야 한다. (변형하지 않아야 함)

그리고 위와 같이 쓰면 student1변수 하나만의 prototype만 변하는 것이기 때문에 Student할당한 것이 아니다.

2) .prototype.prototype 대입: 상속이 아님

var Human = function(name) {
    this.name = name;
}
Human.prototype.sleep = function() {
    console.log('zzz');
}

var Student = function() {}
Student.prototype.learn = function() {
    console.log('배우는 중...');
}


var student1 = new Student();

위와 같이 쓰는건 MyArray.prototype이 Array.prototype을 참조하는것이 되어버려서 할당이 아니다.

3)Object.create()사용

var Human = function(name) {
    this.name = name;
}
Human.prototype.sleep = function() {
    console.log('zzz');
}

var Student = function(name) {
    Human.call(this, name); //혹은 apply 사용
    //현재 Student의 prototype에 constructor가 없는 상태이다.
    //그렇기 때문에 Human의 constructor를 받아와야 한다.
    //Human의 constructor는 Student의 상태를 모르기 때문에 call이나 apply를 사용해서 현재의 this를 넣어줘야 한다.
}

Student.prototype = Object.create(Human.prototype);
Student.prototype.constructor = Student;
Student.prototype.learn = function() {
    console.log('배우는 중...');
}

var student1 = new Student('first');
student1.learn(); //배우는 중...
student1.sleep(); //zzz

참고

CodeStates Immersive Course

YOU DON'T KNOW JS(this와 객체 프로토타입, 비동기와 성능) - 카일 심슨 [한빛미디어]

profile
개발자가 되기 위해 공부하고 있습니다! T-story위주로 사용합니다.

0개의 댓글