author
postNo
status
thumbnail
description
category
tags
createdAt
updatedAt

프로토타입 패턴(Prototype Pattern)

JavaScript에서는 상속이나 캡슐화가 명시적으로 존재하지 않는다. (글을 작성하는 현재는 그렇지는 않다.)
JavaScript에서 OOP개념을 구현하기 위한 패턴으로 이해하면 쉬울 것이다.

JavaScript에서 class 흉내내기

function User () {
  'use strict';
    this.say = function () {
      console.log('Hello, World!');
    };
}

const cho = new User();
cho.say(); // Hello, World!
위 코드와 같이 function 안에서 this를 이용하여 함수를 생성하고, new 연산자를 통해 객체를 생성한다.
const cho = new User();
const lee = new User();

conole.log(cho.say() === lee.say()); // false;
완전할당 연산자===를 이용해 두개를 비교해보면 false가 나온다. cholee는 객체 즉 메모리에 할당되어 주소값이 다르기 때문이다.
위의 코드는 prototype을 이용해 이렇게 작성할수도 있다.
function User () {};
User.prototype.say = function () {
  console.log('Hello, World!');
};

const cho = new User();
cho.say(); // Hello, World!
결과는 동일하다.

현재

글을 작성하는 지금은 JavaScript에는 ES6에 추가된 class가 존재한다.
클래스를 이용하면 Java나 C#에서와 같이 extends를 이용해 상속받을 수 있다.
class User {
  say() {
    console.log('Hello, World!');
  };
};

const cho = new User();
cho.say(); // Hello, World!
와 같이 구현할 수 있다.