생성자함수란?
- new 연산자와 함께 호출하여 객체를 생성하는 함수
생성자 함수에 의해 생성된 객체를 인스턴스라 한다.
자바스크립트는 객체 생성자 함수 이외에도 String, Number, Boolean, Function, Array, Date, RegExp, Promise등의 빌트인 함수를 제공한다.
// String 생성자 함수에 의한 String 객체 생성
const strObj = new String('Lee');
console.log(typeof strObj); // object
console.log(strObj); // String {"Lee"}
// Number 생성자 함수에 의한 Number 객체 생성
const numObj = new Number(123);
console.log(typeof numObj); // object
console.log(numObj); // Number {123}
// Boolean 생성자 함수에 의한 Boolean 객체 생성
const boolObj= new Boolean(true);
console.log(typeof boolObj); // object
console.log(boolObj); // Boolean {true}
// Function 생성자 함수에 의한 Function 객체(함수) 생성
const func = new Function('x', 'return x * x');
console.log(typeof func); // function
console.dir(func); // ƒ anonymous(x)
// Array 생성자 함수에 의한 Array 객체(배열) 생성
const arr = new Array(1, 2, 3);
console.log(typeof arr); // object
console.log(arr); // [1, 2, 3]
// RegExp 생성자 함수에 의한 RegExp 객체(정규 표현식) 생성
const regExp = new RegExp(/ab+c/i);
console.log(typeof regExp); // object
console.log(regExp); // /ab+c/i
// Date 생성자 함수에 의한 Date 객체 생성
const date = new Date();
console.log(typeof date); // object
console.log(date); // Mon May 04 2020 08:36:33 GMT+0900 (대한민국 표준시)
- 객체 리터럴에 의한 객체 생성방식의 문제점
- 프로퍼티 구조가 동일함에도 불구하고 매번 같은 프로퍼티와 매서드를 기술해야한다.
- 생성자 함수의 장점
- 프로퍼티 구조가 동일한 객체 여러개를 간편하게 생성 가능
ex)
// 생성자 함수
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
객체 자신의 프로퍼티나 매서드를 참조하기 위한 자기참조변수다.
this가 가리키는 값, 즉 this 바인딩은 호출 방식에 따라 동적으로 결정된다.
함수 호출 방식 this바인딩(가리키는 값)
1. 일반함수로서의 호출 -> 전역 객체
2. 매서드로서의 호출 -> 매서드를 호출한 객체
3. 생성자 함수로서 호출 -> 생성자 함수가 미래에 생성할 인스턴스
// ex)
function foo() {
console.log(this);
}
// 일반적인 함수로서 호출
// 전역 객체는 브라우저 환경에서는 window, Node.js 환경에서는 global을 가리킨다.
foo(); // window
// 메서드로서 호출
const obj = { foo }; // ES6 프로퍼티 축약 표현
obj.foo(); // obj
// 생성자 함수로서 호출
const inst = new foo(); // inst
function Circle(radius) {
// 1. 암묵적으로 인스턴스가 생성되고 this에 바인딩된다.
// 2. this에 바인딩되어 있는 인스턴스를 초기화한다.
this.radius = radius;
this.getDiameter = function () {
return 2 * this.radius;
};
}
생성자 함수 내부에서 명시적으로 this가 아닌 다른 값을 반환하는 것은 생성자 함수의 기본동작을 훼손하므로 반드시 return문을 생략한다.
함수 객체가 갖고 있는 내부 매서드
function foo() {}
// 일반적인 함수로서 호출: [[Call]]이 호출된다.
foo();
// 생성자 함수로서 호출: [[Construct]]가 호출된다.
new foo();
내부 매서드 [[Call]]을 갖는 함수 객체를 callable이라 하며
내부 매서드 [[Construct]]를 갖는 함수 객체를 non-constructor라 부른다.
constructor : 함수선언문, 함수표현식, 클래스
non-constructor: 매서드(ES6 매서드 축약표현), 화살표 함수