JavaScript에서 객체 생성하기: Factory Function, Constructor Function, Class

MANG·2024년 6월 24일
0
post-thumbnail

JavaScript에서 객체를 생성하는 방법에는 여러 가지가 있습니다. 이번 글에서는 세 가지 주요 방법인 Factory Function, Constructor Function, 그리고 Class를 사용하는 방법에 대해 알아보겠습니다.

1. Object Literal과 Factory Function 사용하기

Factory Function은 객체를 생성하는 함수를 의미합니다. Object Literal을 사용하여 객체를 생성하고, 이를 Factory Function에서 반환하는 방법입니다.

function createUser(email, birthdate) {
  const user = {
    email,
    birthdate,
    buy(item) {
      console.log(`${this.email} buys ${item.name}`);
    },
  };
  return user;
}

const user1 = createUser('chris123@google.com', '1992-03-21');
const user2 = createUser('jerry99@google.com', '1995-07-19');
const user3 = createUser('alice@google.com', '1993-12-24');

장점

  • 간단하고 직관적이다.
  • this 키워드에 대한 혼란이 적다.

단점

  • 메모리 사용량이 많다. 각 객체마다 메소드가 중복 생성된다.

2. Constructor Function 사용하기

Constructor Function은 객체를 생성하기 위해 특별히 만들어진 함수입니다. new 키워드를 사용하여 객체를 생성합니다.

function User(email, birthdate) {
  this.email = email;
  this.birthdate = birthdate;
  this.buy = function (item) {
    console.log(`${this.email} buys ${item.name}`);
  };
}

const user1 = new User('chris123@google.com', '1992-03-21');
const user2 = new User('jerry99@google.com', '1995-07-19');
const user3 = new User('alice@google.com', '1993-12-24');

장점

  • 객체 생성 시 new 키워드를 사용하여 직관적으로 객체 생성 가능.
  • 생성된 객체들은 동일한 프로토타입을 공유하여 메모리 사용을 최적화할 수 있다.

단점

  • 함수 내부에서 this 키워드 사용 시 주의가 필요하다.
  • 상속 구현이 어렵다.

3. Class 키워드 사용하기

class 키워드는 ES6에서 도입된 문법으로, 객체 지향 프로그래밍의 개념을 JavaScript에서 쉽게 사용할 수 있게 해줍니다.

class User {
  constructor(email, birthdate) {
    this.email = email;
    this.birthdate = birthdate;
  }

  buy(item) {
    console.log(`${this.email} buys ${item.name}`);
  }
}

const user1 = new User('chris123@google.com', '1992-03-21');
const user2 = new User('jerry99@google.com', '1995-07-19');
const user3 = new User('alice@google.com', '1993-12-24');

장점

  • 문법이 간결하고 명확하다.
  • 상속 및 확장이 용이하다.
  • 다른 객체 지향 프로그래밍 언어와의 일관성 유지.

단점

  • ES6 이상의 버전에서만 사용 가능하다.

결론

JavaScript에서 객체를 생성하는 방법에는 Factory Function, Constructor Function, 그리고 Class를 사용하는 방법이 있습니다. 각각의 방법에는 장단점이 있으며, 상황에 따라 적절한 방법을 선택해서 사용할 수 있습니다. 앞으로 객체 지향 프로그래밍을 공부할 때는 class 키워드를 주로 사용할 것입니다. 이를 통해 객체 지향의 원리를 쉽게 이해하고, 다른 프로그래밍 언어와의 일관성을 유지할 수 있습니다.

profile
대학생

0개의 댓글