자바스크립트는 new 키워드와 Object, String, Number ... 등의 다양한 생성자 함수를 사용해서 객체를 생성할 수 있다.
단 하나의 객체만 생성 가능하다. 따라서, 프로퍼티 구조가 동일함에도 불구하고 매번 같은 프로퍼티와 메소드를 적어야 한다.
function Circle(radius){
this.radius = radius;
this.getDiameter = function () {
return 2 * this.radius;
}
};
const circle1 = new Circle(5);
const circle2 = new Circle(10);
객체를 생성하기 위한 템플릿처럼 생성자 함수를 사용하여 프로퍼티 구조가 동일한 객체 여러 개를 간편하게 생성할 수 있다.
위의 생성자 함수 내부에서 this는 생성자 함수가 생성할 인스턴스를 가리킨다.
자세한 내용은 다음 글을 참고하자. this란?
생성자 함수는 new 연산자와 함께 호출해야 생성자 함수로 동작한다. 만약 new 연산자와 함께 함수를 호출하지 않으면 일반 함수로 동작한다.
const circle3 = Circle(15);
console.log(circle3); //undefined
console.log(radius); //15 (일반 함수로서 호출된 Circle 내의 this는 전역 객체를 가리킨다.)
function Circle(radius){
console.log(this); //Circle {}
this.radius = radius;
this.getDiameter = function () {
return 2 * this.radius;
}
};
function Circle(radius){
// this에 바인딩되어 있는 인스턴스를 초기화한다.
this.radius = radius;
this.getDiameter = function () {
return 2 * this.radius;
}
};
function Circle(radius){
this.radius = radius;
this.getDiameter = function () {
return 2 * this.radius;
}
};
const circle = new Circle(1);
console.log(circle); // Circle{radius:1, getDiameter:f}
만약 다른 객체를 명시적으로 반환한다면 this가 반환되지 않고 return문에서 명시한 객체가 반환된다. 하지만, 원시값을 반환한다면 암묵적인 this가 반환된다. 명시적으로 다른 값을 반환하는 것은 생성자 함수의 역할을 훼손한다. 따라서, return문을 반드시 생략해야 한다.
function Circle1(radius){
this.radius = radius;
this.getDiameter = function () {
return 2 * this.radius;
}
return {};
};
function Circle2(radius){
// this에 바인딩되어 있는 인스턴스를 초기화한다.
this.radius = radius;
this.getDiameter = function () {
return 2 * this.radius;
}
return 100;
};
const circle1 = new Circle1(1);
const circle2 = new Circle2(1);
console.log(circle1); // {}
console.log(circle2); // Circle{radius:1, getDiameter:f}
일반 객체는 호출할 수 없지만 함수는 호출할 수 있다. 따라서, 함수는 일반 객체가 가지고 있는 내부 슬롯과 내부 메서드는 물론, 함수 객체만을 위한 내부 슬롯과 [[Call]], [[Constructor]]같은 내부 메서드를 추가로 가지고 있다.
함수가 일반 함수로서 호출되면 [[Call]]이 호출되고 new 연산자와 함께 호출되면 [[Construct]]가 호출된다. 따라서, 함수 객체는 callable이면서 constructor이거나 callable이면서 non-constructor이다.
함수 선언문, 함수 표현식, 클래스의 경우 constructor이고, 메서드와 화살표 함수의 경우 non-constructor이다.
여기서 메서드는 함수가 어디에 할당되어 있는지에 따라가 아니라 함수 정의 방식에 따라 결정된다. 일반적으로 ECMAScript 사양에서는 ES6의 메서드 축약 표현만 메서드를 의미한다.
const a = {
x: function(){}; // 일반 함수로 정의됐으므로 메서드로 인정하지 않는다.
};
// ES6의 메서드 축약 표현이므로 메서드로 인정한다.
const b = {
x(){};
};
new a.x(); // x {}
new b.x(); // TypeError: b.x is not a constructor
new 연산자와 함께 함수를 호출하면 생성자 함수로, 없이 호출하면 일반 함수로 호출된다.
// 생성자 함수가 아닌 일반 함수
function add(x,y){
return x+y;
}
let a = new add();
//함수가 객체를 반환하지 않았으므로 반환문이 무시되고, 빈 객체가 생성되어 반환된다.
console.log(a); // {}
// 생성자 함수
function Circle(radius){
this.radius = radius;
this.getDiameter = function () {
return 2 * this.radius;
}
return {};
};
const circle = Circle(5);
console.log(circle); // undefined
// 일반 함수 내부의 this는 전역 객체인 window를 가리킨다.
console.log(radius); // 5
console.log(getDiameter()); // 10
circle.getDiameter(); // TypeError: Cannot read property 'getDiameter' of undefined
혼동을 방지하기 위해 일반적으로 생성자 함수는 파스칼 케이스로 명명하여 일반 함수와 구분짓는다.
함수 내부에서 new.target을 사용하면 생성자 함수로서 호출되었는지 확인할 수 있다.
생성자 함수로서 호출되면 함수 내부의 new.target은 함수 자신을 가리킨다. 일반 함수로서 호출되면 new.target은 undefined를 가리킨다.
function Circle(radius){
// 이 함수가 생성자로 호출되지 않으면 new.target은 undefined이다.
if(!new.target){
// new 연산자와 함께 생성자 함수를 재귀 호출하여 생성된 인스턴스를 반환한다.
return new Circle(radius);
}
this.radius = radius;
this.getDiameter = function () {
return 2 * this.radius;
}
return {};
};
const circle = Circle(5);
console.log(circle.getDiameter()); // 10
new.target은 ES6에서 도입된 최신 문법이다. 이를 활용할 수 없다면 스코프 세이프 생성자 패턴을 활용한다.
function Circle(radius){
// 함수가 new와 함께 호출되면 빈 객체를 생성하고 this에 바인딩한다. 이떼 this와 Circle은 프로토타입에 의해 연결된다.
// 함수가 new와 함께 호출되지 않으면 this는 전역 window 객체를 가리킨다. 즉, this와 Circle은 프로토타입에 의해 연결되지 않는다.
if(!(this instanceof Circle)){
return new Circle(radius);
}
this.radius = radius;
this.getDiameter = function () {
return 2 * this.radius;
}
return {};
};
const circle = Circle(5);
console.log(circle.getDiameter()); // 10
대부분의 빌트인 생성자 함수들은 new 와 같이 호출되었는지를 확인한 후 적절한 값을 반환한다.
하지만, String, Number, Boolean 생성자 함수는 new와 함께 호출시엔 객체를 반환하지만 없이 호출하면 문자열, 숫자, 불리언 값을 반환한다. 이를 활용해 데이터 타입 변환이 가능하다.