JavaScript에서 Object를 생성하는 방법들

Park, Jinyong·2020년 6월 17일
0

Small, but Valuable.

목록 보기
17/19

JavaScript는 OOP를 위해 설계된 언어는 아니지만 프로토타입을 이용해 OOP와 비슷하게 객체를 생성할 수 있는 방법을 제공한다. Functional, Functional Shared, Prototypal, Pesudoclassical 이렇게 총 4가지의 방법이 있다. Pseudoclassical 방법을 주로 사용한다.


Functional

const Car = function(position) {
  const instance = {};
  instance.position = position;
  instance.move = function() {
    this.position += 1;
  }
  return instance;
};

const car1 = Car(5);
const car2 = Car(3);
car1.move();
console.log(car1.position); // 6

인스턴스를 생성할 때마다 새로운 method를 생성하기 때문에 메모리를 그만큼 더 차지하게 된다.

Functional Shared

const extend = function(to, from) {
  for (const key in from) {
    to[key] = from[key];
  }
};

const methods = {};
methods.move = function() {
  this.position += 1;
}

const Car = function(position) {
  const instance = {};
  instance.position = position;
  extend(instance, methods);
  return instance;
}

const car1 = Car(5);
const car2 = Car(3);
car1.move();
console.log(car1.position); // 6

method를 미리 정의해두고 인스턴스를 생성할 때마다 기존 method의 참조를 연결해주는 것으로 메모리를 절약할 수 있다.

Prototypal

const methods = {};
methods.move = function() {
  this.position += 1;
}

const Car = function(position) {
  const instance = Object.create(methods);
  instance.position = position;
  return instance;
}

const car1 = Car(5);
const car2 = Car(3);
car1.move();
console.log(car1.position); // 6

Object.create는 특정 객체를 프로토타입으로 하는 객체를 생성한다.

Pseudoclassical

const Car = function(position) {
  this.position = position;
}

Car.prototype.move = function() {
  this.position += 1;
}

const car1 = new Car(5);
const car2 = new Car(3);
car1.move();
console.log(car1.position); // 6

이 방법으로 하면 new 연산자를 이용하여 인스턴스를 생성해야 한다.


가장 간단하고 명료한 방법으로는 ES6 문법인 class를 사용하여 구현할 수도 있다.

class Car {
  constructor(position) {
    this.position = position;
  }
  move() {
    this.position += 1;
  }
}

const car1 = new Car(5);
const car2 = new Car(3);
car1.move();
console.log(car1.position); // 6

0개의 댓글