728x90
생성자 함수는 이름 그대로 객체를 생성하는 함수이다. 하지만 클래스 기반 객체지향 언어의 생성자와는 다르게 일반 함수와 동일한 방법으로 생성자 함수를 정의하고 new 연산자와 함께 호출하면 해당 함수는 생성자 함수로 동작한다.
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가 아닌 다른 객체를 명시적으로 반환하면 this가 반환되지 못하고
return 문에 명시한 객체가 반환된다.
*/
function Circle(radius) {
this.radius = radius;
this.getDiameter = function() {
return 2 * this.radius;
};
return {};
}
const circle = new Circle(1);
console.log(circle); // {}
/*
하지만 명시적으로 원시 값을 반환하면 원시값은 무시되고 암묵적으로 this가 반환된다.
*/
function Circle(radius) {
this.radius = radius;
this.getDiameter = function() {
return 2 * this.radius;
};
return 100;
}
const circle = new Circle(1);
console.log(circle); // Circle {radius: 1, getDiameter: f}
이처럼 생성자 함수 내부에서 명시적으로 this 가 아닌 값을 반환하는 것은 생성자 함수의 기본 동작을 훼손하기 때문에 반드시 생성자 함수에서는 return을 생략해야 한다.
new 연산자와 함께 함수를 호출하면 해당 함수는 생성자 함수로 동작한다. 즉 함수 객체 내부 메서드인 [[Call]] 이 호출되는 것이 아니라 [[Constructor]]가 호출된다.
728x90
댓글