[JavaScript] Factory Function & Constructor Function

smiley·2022년 4월 28일
0

JavaScript

목록 보기
6/6
post-thumbnail

Factory Function

어떤 함수가 new 키워드 없이 객체를 반환할 때, 이 함수를 공장 함수 혹은 팩토리 함수라 부른다. 객체를 찍어내는 형태이기 때문에 붙은 이름이다.

function person(name, age, gender) {
  const person = {};
  person.name = name;
  person.age = age;
  person.gender = gender;
  
  return person;
}

const person1 = person('emily', 18, 'W');
const person2 = person('tom', 22, 'M');

console.log(person1); // {name: 'emily', age: 18, gender: 'W'}
console.log(person2); // {name: 'tom', age: 22, gender: 'M'}

Constructor Function

어떤 함수가 new 키워드를 사용하여 객체를 생성하는 경우, 이를 생성자 함수라 부른다. 생성자 함수는 유사한 객체를 여러 개 생성해야 할 때 활용하며, 함수명은 대문자로 시작된다.

function Person(name, age, gender) {
  this.name = name;
  this.age = age;
  this.gender = gender;
}

const person3 = new Person('emily', 18, 'W');
const person4 = new Person('tom', 22, 'M');

console.log(person3); // {name: 'emily', age: 18, gender: 'W'}
console.log(person4); // {name: 'tom', age: 22, gender: 'M'}

Factory Function vs Constructor Function

팩토리 함수와 생성자 함수는 모두 객체를 반환한다는 점에서 크게 차이가 없는 것처럼 보일 수 있다. 하지만 각 객체의 __proto__를 자세히 살펴보면 차이점을 발견할 수 있다.

🌼 우선 Factory Function을 통해 생성한 person1을 분석해보자.

person1.__proto__ === person.prototype; // false
person1.__proto__ === Function.prototype; // false
person1.__proto__ === Object.prototype; // true

🌼 다음으로는 Constructor Function을 통해 생성한 person3을 분석해보자.

person3.__proto__ === Person.prototype; // true
person3.__proto__.__proto__ === Object.prototype; // true

👉 person1의 __proto__ 는 Object.prototype을 가리키는 반면,
👉 person3의 __proto__는 constructor function인 Person 함수의 prototype을 가리킨다.

이러한 차이를 이해하기 위해서는 new 키워드를 통한 객체 생성 과정을 알아야 한다.

Constructor Function의 객체 생성 과정

MDN에서는 new 키워드에 대해 다음과 같이 소개한다.

"The new operator lets developers create an instance of a user-defined object type or of one of the built-in object types that has a constructor function."

앞서 작성한 constructor function인 Person( )의 내부 과정을 좀 더 자세히 분석해보자.

function Person(name, age, gender) {
  // (1) this = {}; 빈 객체를 만든다.
  // (2) this.__proto__ = Person.prototype; 생성자 함수의 prototype 대입.
  
  // (3) this에 프로퍼티를 추가한다.
  this.name = name;
  this.age = age;
  this.gender = gender;
  
  // (4) return this
}

const person = new Person('kate', 27, 'W');

👉 즉, constructor function을 new 키워드로 호출함으로써 Person() 함수 내부적으로는 this라는 빈 객체가 생성되고, 이때 this는 생성자 함수의 prototype을 __proto__로 받기 때문에 사용자가 정의한 객체를 더 쉽고 간단하게 만들 수 있도록 도와준다.


출처 :
JavaScript Factory functions vs Constructor functions
MDN Documentation_new operator

profile
하루하루 성장하는 개발자입니다. 배운 것을 기록하고 있습니다.

0개의 댓글