
new 연산자와 함께 Object 생성자 함수를 호출하면 빈 객체를 생성하여 반환한다.
const person = new Object();
person.name = 'Lee';
person.sayHello = function () {
console.log('Hi! My name is ' + this.name);
};
console.log(person); // {name: "Lee", sayHello: ƒ}
person.sayHello(); // Hi! My name is Lee
생성자 함수(constructor)
new 연산자와 함께 호출하여 객체(인스턴스)를 생성하는 함수.
생성자 함수에 의해 생성된 객체를 인스턴스(instance)라고 한다.
Object 생성자 함수 외에도 String, Number, Boolean, Function, Array, Date, RegExp, Promise등의 빌트인 생성자 함수를 제공한다.
객체 리터럴에 의한 객체 생성 방식은 직관적이고 간편하다. 하지만 단 하나의 객체만 생성할 수 있다. 따라서 동일한 프로퍼티를 갖는 객체를 여러개 생성해야 하는 경우 객체 리터럴로 생성하는 방식은 비효율적이다.
const circle1 = {
radius: 5,
getDiameter() {
return 2 * this.radius;
}
};
console.log(circle1.getDiameter()); // 10
const circle2 = {
radius: 10,
getDiameter() {
return 2 * this.radius;
}
};
console.log(circle2.getDiameter()); // 20
생성자 함수를 사용하면 템플릿(클래스)처럼 프로퍼티가 동일한 구조의 객체를 여러개 생성할 수 있다. 이런 경우 생성자 함수를 사용하는 것이 효율적이다.
// 생성자 함수
function Circle(radius) {
// 생성자 함수 내부의 this는 생성자 함수가 생성할 인스턴스를 가리킨다.
this.radius = radius;
this.getDiameter = function () {
return 2 * this.radius;
};
}
// 인스턴스의 생성
const circle1 = new Circle(5); // 반지름이 5인 Circle 객체를 생성
const circle2 = new Circle(10); // 반지름이 10인 Circle 객체를 생성
console.log(circle1.getDiameter()); // 10
console.log(circle2.getDiameter()); // 20
생성자 함수의 역할은 프로퍼티 구조가 동일한 인스턴스를 생성하기 위한 템플릿(클래스)으로서 동작하여 인스턴스를 생성하는 것과 생성된 인스턴스를 초기화(인스턴스 프로퍼티 추가 및 초기값 할당)하는 것이다.
new 연산자와 함께 생성자 함수를 호출하면 자바스크립트 엔진은 다음과 같은 과정을 거쳐 암묵적으로 인스턴스를 생성하고 인스턴스를 초기화한 후 암묵적으로 인스턴스를 반환한다.
function Circle(radius) {
// 1. 암묵적으로 빈 객체가 생성되고 this에 바인딩된다.
console.log(this); // Circle {}
this.radius = radius;
this.getDiameter = function () {
return 2 * this.radius;
};
}
생성자 함수에 기술되어 있는 코드가 한 줄씩 실행되어 this에 바인딩되어 있는 인스턴스를 초기화한다. 인스턴스에 프로퍼티나 메서드를 추가하고 생성자 함수가 인수로 전달받은 초기값을 할당한다.
function Circle(radius) {
// 1. 암묵적으로 인스턴스가 생성되고 this에 바인딩된다.
// 2. this에 바인딩되어 있는 인스턴스를 초기화한다.
this.radius = radius;
this.getDiameter = function () {
return 2 * this.radius;
};
}
생성자 함수 내부의 모든 처리가 끝나면 완성된 인스턴스가 바인딩된 this가 암묵적으로 반환된다.
function Circle(radius) {
// 1. 암묵적으로 인스턴스가 생성되고 this에 바인딩된다.
// 2. this에 바인딩되어 있는 인스턴스를 초기화한다.
this.radius = radius;
this.getDiameter = function () {
return 2 * this.radius;
};
// 3. 완성된 인스턴스가 바인딩된 this가 암묵적으로 반환된다
}
// 인스턴스 생성. Circle 생성자 함수는 암묵적으로 this를 반환한다.
const circle = new Circle(1);
console.log(circle); // Circle {radius: 1, getDiameter: ƒ}
만약
this가 아닌 다른 객체를 명시적으로 반환하면this가 반환되기 못하고return문에 명시한 객체가 반환된다. 즉, 명시적으로 객체를 반환하면 암묵적인 this 반환이 무시된다.
function Circle(radius) {
// 1. 암묵적으로 인스턴스가 생성되고 this에 바인딩된다.
// 2. this에 바인딩되어 있는 인스턴스를 초기화한다.
this.radius = radius;
this.getDiameter = function () {
return 2 * this.radius;
};
// 3. 암묵적으로 this를 반환한다.
// 명시적으로 객체를 반환하면 암묵적인 this 반환이 무시된다.
return {};
}
// 인스턴스 생성. Circle 생성자 함수는 명시적으로 반환한 객체를 반환한다.
const circle = new Circle(1);
console.log(circle); // {}
또한 명시적으로 원시 값을 반환하면 원시 값 반환은 무시되고 암묵적으로 this가 반환된다.
function Circle(radius) {
// 1. 암묵적으로 인스턴스가 생성되고 this에 바인딩된다.
// 2. this에 바인딩되어 있는 인스턴스를 초기화한다.
this.radius = radius;
this.getDiameter = function () {
return 2 * this.radius;
};
// 3. 암묵적으로 this를 반환한다.
// 명시적으로 원시값을 반환하면 원시값 반환은 무시되고 암묵적으로 this가 반환된다.
return 100;
}
// 인스턴스 생성. Circle 생성자 함수는 명시적으로 반환한 객체를 반환한다.
const circle = new Circle(1);
console.log(circle); // Circle {radius: 1, getDiameter: ƒ}
함수 선언문 또는 함수 표현식으로 정의한 함수는 일반적인 함수로서 호출할 수 있는 것은 물론 생성자 함수로서 호출할 수 있다. 생성자 함수로서 호출한다는 것은 new 연산자와 함께 호출하여 객체를 생성하는 것을 의미한다.
function foo() {}
// 일반적인 함수로서 호출: [[Call]]이 호출된다.
foo();
// 생성자 함수로서 호출: [[Construct]]가 호출된다.
new foo();
함수가 일반 함수로서 호출되면
[[Call]]이 호출되고, new연산자와 함께 생성자 함수로서 호출되면[[Construct]]가 호출된다.
내부 메서드 [[Call]]을 갖는 함수 객체를 callable이라 하며, 내부 메서드 [[Construct]]를 갖는 함수 객체를 constructor, [[Construct]]를 갖지 않는 함수 객체를 non-constructor라고 부른다.

callable : 호출할 수 있는 객체
constructor : 생성자 함수로서 호출할 수 있는 함수
non-constructor : 객체를 생성자 함수로서 호출할 수 없는 함수
함수 객체는 반드시 callable이어야 한다. 따라서 모든 함수 객체는 내부 메서드 [[Call]]을 갖고 있으므로 호출할 수 있다. 하지만 모든 함수 객체가 [[Construct]]를 갖는 것은 아니다. 함수 객체는 constructor일 수도 있고 non-constructor일 수도 있다.
자바스크립트 엔진은 함수 정의를 평가하여 함수 객체를 생성할 때 함수 정의 방식에 따라 함수를 constructor와 non-constructor으로 구분한다.
constructor : 함수 선언문, 함수 표현식, 클래스(클래스도 함수)
non-constructor : 메서드(ES6 메서드 축약 표현), 화살표 함수
// 일반 함수 정의: 함수 선언문, 함수 표현식
function foo() {}
const bar = function () {};
// 프로퍼티 x의 값으로 할당된 것은 일반 함수로 정의된 함수다. 이는 메서드로 인정하지 않는다.
const baz = {
x: function () {}
};
// 일반 함수로 정의된 함수만이 constructor이다.
new foo(); // -> foo {}
new bar(); // -> bar {}
new baz.x(); // -> x {}
// 화살표 함수 정의
const arrow = () => {};
new arrow(); // TypeError: arrow is not a constructor
// 메서드 정의: ES6의 메서드 축약 표현만을 메서드로 인정한다.
const obj = {
x() {}
};
new obj.x(); // TypeError: obj.x is not a constructor
new연산자와 함께 함수를 호출하면 해당 함수는 생성자 함수로 동작한다.
함수 객체의 내부 메서드 [[Call]]이 호출되는 것이 아니라 [[Construct]]가 호출된다. 단, new연산자와 함께 호출하는 함수는 non-constructor가 아닌 constructor이어야 한다.
반대로 new연산자 없이 호출하면 일반 함수로 호출된다. 즉, 함수 객체의 내부 메서드 [[Construct]]가 호출되는 것이 아니라 [[Call]]이 호출된다.
// 생성자 함수
function Circle(radius) {
this.radius = radius;
this.getDiameter = function () {
return 2 * this.radius;
};
}
// new 연산자 없이 생성자 함수 호출하면 일반 함수로서 호출된다.
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연산자 없이 호출되는 것을 방지하기 위해 파스칼 케이스 컨벤션을 사용하지만, 그래도 실수는 발생할 수 있다.
new.target연산자는 this와 유사하게 constructor인 모든 함수 내부에서 암묵적인 지역변수와 같이 사용되며 메타 프로퍼티라고 부른다.(IE는 지원안함)
함수 내부에서 new.target을 사용하면 new 연산자와 함계 생성자 함수로서 호출되었는지 확인할 수 있다.
new 연산자와 함께 생성자 함수로서 호출되면 함수 내부의 new.target은 함수 자신을 가리킨다. new 연산자 없이 일반 함수로 호출되면 undefined를 반환한다.
// 생성자 함수
function Circle(radius){
// 이 함수가 new 연산자와 함께 호출되지 않았다면 new.target은 undefined다.
if(!new.target){
return new Circle(radius)
}
this.radius = radius;
this.getDiameter = function(){
return 2 * this.radius
}
console.log(this.getDiameter()) //10 20
}
// new 연산자 없이 생성자 함수를 호출하여도 new.target을 통해 생성자 함수로서 호출된다.
const cir1 = new Circle(5);
console.log(cir1) // Circle {radius: 5, getDiameter: ƒ}
const cir3 = Circle(10);
console.log(cir3) // Circle {radius: 10, getDiameter: ƒ}
console.log(cir1.getDiameter()) // 10
console.log(cir3.getDiameter()) // 20
참고 자료
모던 자바스크립트 Deep Dive