JavaScript에서 객체를 생성하는 방법에는 여러 가지가 있습니다. 이번 글에서는 세 가지 주요 방법인 Factory Function, Constructor Function, 그리고 Class를 사용하는 방법에 대해 알아보겠습니다.
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
키워드에 대한 혼란이 적다.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
키워드 사용 시 주의가 필요하다.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');
JavaScript에서 객체를 생성하는 방법에는 Factory Function, Constructor Function, 그리고 Class를 사용하는 방법이 있습니다. 각각의 방법에는 장단점이 있으며, 상황에 따라 적절한 방법을 선택해서 사용할 수 있습니다. 앞으로 객체 지향 프로그래밍을 공부할 때는 class
키워드를 주로 사용할 것입니다. 이를 통해 객체 지향의 원리를 쉽게 이해하고, 다른 프로그래밍 언어와의 일관성을 유지할 수 있습니다.