Node.js 공부기록 (5) 프로토타입

Node.js 공부기록 (5) 프로토타입

자바스크립트에서 상속을 구현 가능한 개념인 프로토타입

함수형으로 짜거나, OOP와 관계없이 작성하면 프로토타입을 다루지 않을 수도 있음.

function Student(name) {

    this.name = name

}

현재 js에서 클래스라는 키워드를 제공하긴 하지만,

클래스라는 키워드가 존재하기 전에는, 함수를 정의하듯이 “function 클래스명” 으로 클래스를 만들어왔다.

js의 클래스는 사실상 프로토타입을 기반으로 한 function 이다.

const me = new Student(‘Jeongho’)

console.log(me)

실행하면

Student { name: ‘Jeongho’ }가 찍힌다.

me.name 을 찍을 수도 있지만,

me.toString() 을 사용할 수도 있다.

프로토타입 체인이라는 개념이 있음.

가장 상위부터 찾는다는 개념임. 상위에서 가장 가까운 것을 찾음.

me.name 은 가장 상위에 갖고 있다. toString() 은 가장 상위에 없으므로, 그 하위인 프로토타입 안에서 찾는다.

function Student(name) {

    this.name = name

}

Student.prototype.greet = function greet() {

    return `Hi, ${this.name}!`

}

const me = new Student(‘Jeongho’)

console.log(me.greet())

상속 구조를 만들어보자.

/* eslint-disable */

function Person(name) {

  this.name = name

}

Person.prototype.greet = function greet() {

  return `Hi, ${this.name}!`

}

function Student(name) {

  // 부모의 생성자 실행

  this.__proto__.constructor(name)

}

Student.prototype.study = function study() {

  return `${this.name} is studying.`

}

// Student의 프로토타입을 Person 프로토타입으로 지정 (상속)

Object.setPrototypeOf(Student.prototype, Person.prototype)

const me = new Student(‘Jeongho’)

console.log(me.greet())

console.log(me.study())

* instance of

const me = new Student(‘Jeongho’)

console.log(me instanceof Student)

console.log(me instanceof Person)

둘 다 true로 나온다.

const anotherPerson = new Person(‘Foo’)

console.log(anotherPerson instanceof Student)

console.log(anotherPerson instanceof Person)

순서대로 false, true가 나온다.

instance of 는 어레이 검사에 좋다.

[] instance of Array 는 true가 나온다.

물론 어레이는 오브젝트 이기도 하므로, [] instance of Object 도 true가 나온다.

지금까지의 설명은 ES5이다.

같은 내용을 클래스로 다시 해보자. (ES6)

/* eslint-disable */

class Person {

  constructor(name) {

    this.name = name

  }

  greet() {

    return `Hi, ${this.name}.`

  }

}

class Student extends Person {

  constructor(name) {

    super(name)

  }

  study() {

    return `${this.name} is studying.`

  }

}

const me = new Student(‘JeongHo’)

console.log(me.study())

console.log(me.greet())

클래스 역시 프로토타입 체인을 활용한 것이다. (내부적으로 앞의 것과 다를바 없다)

클래스는 신택틱 슈거일 뿐이다.

syntactic sugar

문법적 설탕, 신택틱 슈거

– 사람이 이해하기 쉽고 표현하기 쉽게 컴퓨터 언어를 디자인해 놓은 문맥

– 내부적인 동작은 기존과 동일하지만, 어떤 구현 방식에 맞추어 새로운 문법을 제공하는 경우를 가리킴