new 연산자 => 첫 문자는 대문자
일반함수와 생성자 함수의 특별한 형식적 차이는 없음.
new 연산자와 함께 함수를 호출하면 해당 함수는 생성자함수로 동작함.
함수 객체 내부 메서드 [[Call]]이 호출되는 것이 아닌 [[Constructor]]가 호출됨.
new 연산자와 함께 호출하는 함수는 non-constructor가 아닌 constructor여야 함.
function Circle(radius) {
this.radius = radius;
this.getDiameter = function () {
return 2 * this.radius;
};
}
const circle = Circle(5); //new연산자 없이 호출하면 일반함수로 호출.
console.log(circle); //undefined
console.log(radius); //5
console.log(getDiameter()); //10 일반함수호출을 했기 때문에 this는 window를 가리킴
//따라서 radius 프로퍼티와 getDiameter 메서드는 전역객체의 프로퍼티와 메서드가 됨.
circle.getDiameter(); //TypeError : can not read property 'getDiameter' of undefined
출처 : 모던 자바스크립트 deep dive
'javascript' 카테고리의 다른 글
webpack (0) | 2024.02.24 |
---|---|
break && continue (0) | 2022.03.05 |
Prototype method vs Object method (0) | 2022.02.27 |
if..else / if.. else if (0) | 2022.02.27 |
Early Return (0) | 2022.02.27 |