17.1 Object 생성자 함수
- 생성자 함수(constructor) : new 연산자와 함께 호출하여 객체(인스턴스)를 생성하는 함수
- 인스턴스(instance) : 생성자 함수에 의해 생성된 객체
자바스크립트는 Object 생성자 함수 외에도 String, Number, Boolean, Function, Array, Date, RegExp, Promise 등의 빌트인에 생성자 함수를 제공
// 빈 객체의 생성
const person = new Object();
// 프로퍼티 추가
person.name = 'Lee';
person.sayHello = function () {
console.log('Hi: My name is ' + this.name);
};
console.log(person); // {name: "Lee", sayHello: f}
person.sayHello(); // Hi! My name is Lee
// 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 (대한민국 표준시)
17.2 생성자 함수
17.2.1 객체 리터럴에 의한 객체 생성 방식의 문제점
객체 리터럴에 의한 객체 생성 방식
- 직관적이고 간편
-단 하나의 객체만 생성
- 동일한 프로퍼티를 갖는 객체를 여러 개 생성해야 하는 경우 매번 같은 프로퍼티를 기술해야 하기 때문에 비효율적
const circlel = {
radius: 5,
getDiameter() {
return 2 * this.radius;
},
};
console.log(circlel.getDiameter()); // 10
const circle2 = {
radius: 10,
getDiameter() {
return 2 * this.radius;
},
};
console.log(circle2.getDiameter()); // 20
프로퍼티는 객체마다 프로퍼티 값이 다를 수 있지만 메서드는 내용이 동일한 경우가 일반적임
때문에 객체 리터럴에 의해 객체를 생성하는 경우 프로퍼티 구조가 동일함에도 불구하고 매번 같은 프로퍼티와 메서드를 기술해야 함
17.2.2 생성자 함수에 의한 객체 생성 방식의 장점
- 객체(인스턴스)를 생성하기 위한 템플릿(클래스)처럼 생성자 함수를 사용하여 프로퍼티 구조가 동일한 객체 여러 개를 간편하게 생성 가능
- new 연산자와 함께 호출하면 생성자 함수로, new 연산자와 함께 호출하지 않으면 일반 함수로 동작함
// 생성자 함수
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 연산자와 함께 호출하지 않으면 생성자 함수로 동작하지 않음
// 즉,일반 함수로서 호출됨
const circle3 = Circle(15);
//일반 함수로서 호출된 Circle은 반환문이 없으므로 암묵적으로 undefined 반환
console.log(circle3); // undefined
// 일반 함수로서 호출된 Circle 내의 this는 전역 객체를 가리킴
console.log(radius); // 15
17.2.3 생성자 함수의 인스턴스 생성 과정
( 1 ) 인스턴스 생성과 this 바인딩
- 암묵적으로 빈 객체, 인스턴스가 생성되고 이는 this에 바인딩됨
*바인딩 : 식별자와 값을 연결하는 과정
function Circle(radius) {
// 1. 암묵적으로 인스턴스가 생성되고 this에 바인딩됨
console.log(this); // Circle {}
this.radi니s = radius;
this.getDiameter = function () {
return 2 * this.radius;
};
}
( 2 ) 인스턴스 초기화
- this에 바인딩되어 있는 인스턴스를 초기화
function Circle(radius) {
// 1. 암묵적으로 인스턴스가 생성되고 this에 바인딩됨
// 2. this에 바인딩되어 있는 인스턴스를 초기화
this.radius = radius;
this.getDiameter = function () {
return 2 * this.radius;
};
}
( 3 ) 인스턴스 변환
- 생성자 함수 내부에서 모든 처리가 끝나면 완성된 인스턴스가 바인딩된 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: f}
17.2.4 내부메서드 [[Call]]과 [[Construct]]
- 함수는 객체이므로 일반객체와 동일하게 내부 슬롯과 내부 메서드를 모두 가지고 있음
//함수는 객체
function foo() { }
// 함수는 객체이므로 프로퍼티를 소유 가능
foo.prop = 10;
// 함수는 객체이므로 메서드를 소유 가능
foo.method = function () {
console.log(this.prop);
};
foo.method(); // 10
- 일반 객체는 호출할 수 없지만 함수는 호출 가능
- 함수 객체는 일반 객체가 가지고 있는 내부 슬롯과 내부 메서드, 함수로서 동작하기 위해 함수 객체만을 위한
[[Environment]], [[FormalParameters]] 등의 내부 슬롯, [[Call]], [[Construct]] 같은 내부 메서드를 추가로 가지고 있음
➔ 함수가 일반 함수로서 호출되면 함수 객체의 내부 메서드 [[Call]]이 호출되고 new 연산자와 함께 생성자 함수로서 호출되면 내부 메서드 [[Construct]]가 호출
function foo() {}
// 일반적인 함수로서 호출 : [[Call]] 호출
foo();
//생성자 함수로서 호출 : [[Construct]] 호출
new foo();
- callable : 내부 메서드 [[Call]]을 갖는 함수 객체, 호출할 수 있는 객체 ,즉 함수
- constructor : 내부 메서드 [[Construct]]를 갖는 함수 객체
- non—constructor : [ [Construct] ]를 갖지 않는 함수 객체, 객체를 생성자 함수로서 호출할 수 없는 함수
➔ 함수 객체는 callable이면서 constructor이거나 callable이면서 non-constructor
즉, 모든 함수 객체는 호출할 수 있지만 모든 함수 객체를 생성자 함수로서 호출할 수 있는 것은 아님
17.2.5 constructor와 non-constructor의 구분
constructor: 함수 선언문, 함수 표현식,클래스(클래스도 함수)
non-constructor: 메서드(ES6 메서드 축약 표현), 화살표 함수
17.2.6 new 연산자
- new 연산자와 함께 함수를 호출하면 해당 함수는 생성자 함수로 동작
- 함수 객체의 내부 메서드 [[Call]]이 호출되는 것이 아니라 [[Construct]] 호출
- 단, new 연산자와 함께 호출하는 함수는 non-constructor가 아닌 constructor이어야 함
// 생성자 함수로서 정의하지 않은 일반 함수
function add(x, y) {
return x + y;
}
// 생성자 함수로서 정의하지 않은 일반 함수를 new 연산자와 함께 호출
let inst = new add();
// 함수가 객처» 반환하지 않았으므로 반환문이 무시됨
// 따라서 빈 객체가 생성되어 반환됨
console.log(inst); // {}
// 객체를 반환하는 일반 함수
function createUser(name, role) {
return { name, role };
}
// 일반 함수를 new 연산자와 함께 호출
inst = new createUser('Lee', 'admin');
// 함수가 생성한 객체를 반환
console.log(inst); // {name: "Lee", role: "admin"}
17.2.7 new.target
- new 연산자와 함께 생성자 함수로서 호출되면 함수 내부의 new.target은 함수 자신을 가리킴
- new 연산자 없이 일반 함수로서 호출된 함수 내부의 new.target은 undefined임
// 생성자 함수
function Circle(radius) {
// 이 함수가 new 연산자와 함께 호출되지 않았다면 new. target은 undefined
if (!new.target) {
// new 연산자와 함께 생성자 함수를 재귀 호출하여 생성된 인스턴스를 반환
return new Circle(radius);
}
this.radius = radius;
this.getDiameter = function () {
return 2 * this.radius;
};
}
// new 연산자 없이 생성자 함수를 호출하여도 new. target을 통해 생성자 함수로서 호출
const circle = Circle(5);
console.log(circle.getDiameter());
'🦎모던 자바스크립트 Deep Dive' 카테고리의 다른 글
[Chap 20]strict mode (0) | 2024.05.29 |
---|---|
[Chap 19] 프로토타입 (0) | 2024.05.22 |
[Chap 15] 스코프 (0) | 2024.05.07 |
[Chap 13] 스코프 (0) | 2024.05.01 |
[Chap 12] 함수 (0) | 2024.04.16 |