Modern JavaScript Deep Dive 스터디 - CH17 생성자 함수에 의한 객체 생성
참고 자료: ⟪모던 자바스크립트 Deep Dive⟫"(이웅모 지음,위키북스, 2020)
- 인스턴스(instance) : 생성자 함수에 의해 생성된 객체
// 빈 객체의 생성
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
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
this
객체 자신의 프로퍼티나 메서드를 참조하기 위한 자기 참조 변수
함수 호출 방식 this가 가리키는 값(this 바인딩) 일반 함수로서 호출 전역 객체 메서드로서 호출 메서드를 호출한 객체(마침표 앞의 객체) 생성자 함수로서 호출 생성자 함수가 생성할 인스턴스
자바스크립트에서 생성자 함수
- 일반적인 클래스 기반 객체지향언어에서 생성자와는 다르게, 자바스크립트에서 생성자는 형식이 정해져 있지 않음
- 일반 함수와 동일한 방법으로 생성자 함수를 정의 -> new 연산자와 함께 호출 -> 생성자 함수로 동작
- new 연산자 와 함께 생성자 함수를 호출하지 않으면 일반 함수로 동작
function Circle(radius) {
// 1. 암묵적으로 빈 객체가 생성되고 this에 바인딩된다.
console.log(this); // Circle {}
this.radius = radius;
this.getDiameter = function () {
return 2 * this.radius;
};
}
function Circle(radius) {
// 1. 암묵적으로 인스턴스가 생성되고 this에 바인딩된다.
// 2. this에 바인딩되어 있는 인스턴스를 초기화한다.
this.radius = radius;
this.getDiameter = function () {
return 2 * this.radius;
};
}
###바인딩
- 식별자와 값을 연결하는 과정
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: ƒ}
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); // {}
function Circle2(radius) {
// 1. 암묵적으로 인스턴스가 생성되고 this에 바인딩된다.
// 2. this에 바인딩되어 있는 인스턴스를 초기화한다.
this.radius = radius;
this.getDiameter = function () {
return 2 * this.radius;
};
// 3. 암묵적으로 this를 반환한다.
// 명시적으로 원시값을 반환하면 원시값 반환은 무시되고 암묵적으로 this가 반환된다.
return 100;
}
// 인스턴스 생성. Circle 생성자 함수는 명시적으로 반환한 객체를 반환한다.
const circle2 = new Circle2(1);
console.log(circle2); // Circle2 {radius: 1, getDiameter: ƒ}
[[Environment]]
, [[FormalParameters]]
등의 내부 슬롯과 [[Call]]
, [[Construct]]
등의 내부 메서드를 추가로 가지고 있기 때문[[Call]]
: 함수가 일반 함수로 호출되면 함수 객체 내부 메서드 [[Call]]
이 호출 [[Construct]]
: 수가 생성자 함수로 호출되면[[Construct]]
이 호출callable, constructor, non-constructor
- callable: 내부 메서드
[[Call]]
을 갖는 함수 객체- constructor: 내부 메서드
[[Construct]]
을 갖는 함수 객체 -> 생성자 함수로 호출 가능.
- 함수 선언문 , 함수 표현식- non-constructor: 내부 메서드
[[Construct]]
을 갖지 않는 함수 객체 -> 생성자 함수로 호출 불가.
- 화살표 함수 , 메서드(ES6 메서드 축약 표현)
- 모든 함수 객체는 반드시 내부 메서드
[[Call]]
을 가지고 있음- 모든 함수 객체가
[[Construct]]
을 가지고 있는 것은 아님
ECMAScript 사양에서 메서드는 ES6 메서드 축약 표현만을 의미
=> 함수가 어디에 할당되어 있는지에 따라 메서드인지를 판단하는 것이 아니라
함수 정의 방식에 따라 constructor과 non-constructor를 구분
function foo() {}
// 일반적인 함수로서 호출: [[Call]]이 호출
foo();
// 생성자 함수로서 호출: [[Construct]]가 호출
new foo();
PascalCase
로 명명하여 일반 함수와 구별하여 사용new.target
은 함수 자신을 가리킴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());
스코프 세이프 생성자 패턴
- IE 같은 new.target 을 지원하지 않는 브라우저 환경에서, 생성자 함수를 보장하는 방법
// Scope-Safe Constructor Pattern
function Circle(radius) {
// 생성자 함수가 new 연산자와 함께 호출되면 함수의 선두에서 빈 객체를 생성하고
// this에 바인딩한다. 이때 this와 Circle은 프로토타입에 의해 연결된다.
// 이 함수가 new 연산자와 함께 호출되지 않았다면 이 시점의 this는 전역 객체 window를 가리킨다.
// 즉, this와 Circle은 프로토타입에 의해 연결되지 않는다.
if (!(this instanceof Circle)) {
// new 연산자와 함께 호출하여 생성된 인스턴스를 반환한다.
return new Circle(radius);
}
this.radius = radius;
this.getDiameter = function () {
return 2 * this.radius;
};
}
// new 연산자 없이 생성자 함수를 호출하여도 생성자 함수로서 호출된다.
const circle = Circle(5);
console.log(circle.getDiameter()); // 10
new
연산자와 함께 호출되었는지를 확인 후 적절한 값을 반환const str = String(123);
console.log(str, typeof str); // 123 string
const num = Number('123');
console.log(num, typeof num); // 123 number
const bool = Boolean('true');
console.log(bool, typeof bool); // true boolean