Web

[JS] 객체 생성하기 (factory function, constructor function, class)

RealJuney 2023. 6. 25. 07:34

1. Factory function

아래 코드와 같이, 함수에서 객체를 하나 생성한 뒤 리턴해주는 방식을 factory function 이라고 한다.

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

const user = createUser('juney@kaist.ac.kr', '20021007');

 

2. Constructor function

new 오퍼레이터를 사용하면, this를 user 객체로 되게끔한다. 따라서 this와 new를 이용하여 다음과 같은 방식으로 constructor function을 만들어 객체를 생성할 수 있다.

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

const user = new User('juney@kaist.ac.kr', '20021007');

 

3. class

객체 지향 언어에서 보편적으로 등장하는 class를 이용하여 객체를 만들 수 있다. 마찬가지로 new 키워드를 사용하지만, property는 constructor 안에, method는 밖에 정의한다.

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

const user = new User('juney@kaist.ac.kr', '20021007');