J.BF Story

[Javascript] Factory Pattern vs Constructor Function vs Class 본문

FrontEnd/Javascript

[Javascript] Factory Pattern vs Constructor Function vs Class

J.BF 2022. 6. 8. 18:58
Factory Pattern (팩토리 패턴)
Constructor Function (생성자 함수)
Class (클래스)

Javascript에서 Object를 만들 때 이용하는 방법들이다

Javascript에서 Class는 ES6 이후에 생긴 개념이므로 그 전에는 Factory Pattern과 Constructor Function을 사용했었다.

대부분 동일한 기능을 가지고있으나 각기 다른 특징을 가지고 있다.

 

Factory Pattern (팩토리 패턴)

function User(id, pw, position) {
	return {
		id: id,
		pw: pw,
		position: position,
		isAdmin() {
			return (this.position == "admin" || this.position == "root");
		}
	};
}

const user1 = User("test1", "1234", "basic");
const user2 = User("test2", "4321", "admin");
  • 'new' operator 없이 호출하여 생성한다.
  • return을 통해 객체를 전달한다.

 

 

Constructor Function (생성자 함수)

function User(id, pw, position) {
	this.id = id;
	this.pw = pw;
	this.position = position;
}

User.prototype.isAdmin = function () {
	return (this.position == "admin" || this.position == "root");
};

const user1 = new User("test1", "1234", "basic");
const user2 = new User("test2", "4321", "admin");
  • 'new' operator로 생성한다.
  • 실수로 'new' operator를 붙여주지않을 시, Function 내부의 'this'는 'window'가 된다.
    (잘못된 값을 가져오거나 수정할 위험이 있다.)
  • prototype을 추가해서 함수를 선언해야한다.
  • 실수로 동일한 이름의 함수를 중복해서 선언할 수 있다.
    (전의 함수는 덮어쓰여짐)

 

Class (클래스)

function User(id, pw, position) {
	constructor(id, pw, position) {
		this.id = id;
		this.pw = pw;
		this.position = position;
	}
	isAdmin() {
		return (this.position == "admin" || this.position == "root");
	}
}

const user1 = new User("test1", "1234", "basic");
const user2 = new User("test2", "4321", "admin");
  • 'new' operator로 생성한다.
  • 실수로 'new' operator를 붙여주지않을 시, 에러를 발생시킨다.
    • 에러메세지: Uncaught TypeError: Class constructor asdf cannot be invoked without 'new'
  • 높은 직관성을 가지고 있으며 실수 방지한다. (함수 중복, 'new' operator 누락)

 

 

참조

https://medium.com/javascript-scene/javascript-factory-functions-vs-constructor-functions-vs-classes-2f22ceddf33e

https://steemit.com/kr/@wonsama/javascript-class-vs-factory

'FrontEnd > Javascript' 카테고리의 다른 글

[Javascript] 값 체크 함수 모음 (커스텀)  (0) 2022.06.21
[Javascript] LocalStorage  (0) 2022.06.19
[Javascript] Random  (0) 2022.03.15
[Javascript] String Format  (0) 2022.03.14
[노마드코더] Events  (0) 2022.03.14
Comments