[JS] Prototype & Class

soor.dev·2021년 4월 10일
0

Java Script

목록 보기
15/26
post-thumbnail

Prototype

➡️ 원형객체 (original form)

자바스크립트에는 class의 개념이 없었다.
대신 prototype이 존재하며, 자바스크립트는 prototype 기반 언어라고 불린다. class가 없으니 prototype을 기반으로 상속을 구현하여 사용해 왔다.

ES6 표준에서 class 문법이 추가되었으나, 자바스크립트가 class기반으로 바뀌어다는 것은 아니다.

Prototype chain : 상속의 이해 !

모든 객체의 상위 객체Object 이다.
( toString()을 작성하지 않아도 모근 객체에서 사용할 수 있는 이유 ➡ 상속 !! )

상위 prototype 객체를 상속받은 하위객체는 그 하위객체에서 또 상속받고, 이렇게 상속되는 일이 반복된다. 이렇게 서로 연결되어 있는 것을 prototype chain이라고 한다.


prototype 연습

let Common = function (name) {
  this.name = name; // property 생성
  this.color = 'green';
}

// Common -> prototype 형성
Common.prototype.ethnic = function () {  // method
  return `${this.name} is from Korea`;
}

let hyunsoo = new Common('Hyunsoo'); // 생성자함수 new Common()의 instance

let Person = function (name) {
  Common.call(this, name);
  this.sports = 'free diving';
  this.coffee = 'latte';
}

// Person의 method를 Object.create하기 전에 생성해 버리면,
// 연결이 되지 않아 나중에 생성자 함수 new()를 만들었을때, 
// 이 부분은 실행되지 않음 => constructor 연결 후에 작성!!
// Person.prototype.quote = function () {
//  return 'Rather be dead than cool';
// } 

Person.prototype = Object.create(Common.prototype);
Person.prototype.constructor = Person;
Person.prototype.quote = function () {
  return 'Rather be dead than cool';
}

let heeni = new Person('Heeni');

class 로 간단하게!

super

  • 상속받을 prototype의 속성들을 전부 가져오는 것이다.
  • prototype의 call, apply와 비슷한 역할을 한다.

constructor

  • 객체의 기본 상태를 설정해주는 생성자이며, 함수 인자를 넣는 것 처럼 ( )안에 넣을 수 있다.
  • 하나의 class는 하나의 constructor라는 이름을 가진 메서드를 갖는다.

class 연습

class Common {
    constructor(name) {
        this.name = name;
        this.color = 'green';
    }
    ethnic() {
        return `${this.name} is from Korea`;
    }
}

let hyunsoo = new Common('Hyunsoo');

class Person extends Common {
    constructor(name) {
        super(name);
        this.sports = 'free diving';
        this.food = 'kimchi';
    }
    quote() {
        return 'Rather be dead than cool';
    }
}

let heeni = new Person('Heeni');

생성자함수 읽어볼 것

0개의 댓글