function Person (name, age) { this.name = name; this.age = age; } const hth = new Person("hth", 28); console.log(hth);
자바스크립트에서는 함수의
return
값이 없으면undefined
가 반환되는데, 위 예제에서는Person
함수는return
값이 없는데도hth
변수에 어떠한 객체가 담긴다.* 생성자 함수의 기본
return
값은this
이고 일반적으로는return
값을 따로 명시하진 않는다.
const arr = []; const obj = {}; const func = function() {};
우리는 보통 자바스크립트에서 객체를 생성할때 위와 같이 사용한다.
const arr = new Array(); const obj = new Object(); const func = new Function();
위 예제 코드처럼 작성해도 실제로는 자바스크립트 내부적으로 아래의 예제코드와 같이 동작한다.
function foo() { console.log("hello"); } const xxx = new foo();
생성자 함수의 기본
return
값은this
이다. 그this
의 값은 새로운 빈 객체이다.
생성자 함수가 반환해주는 빈 객체를 Instance(인스턴스) 라고 부른다.function Person (name, age) { this.name = name; this.age = age; } const hth = new Person("hth", 28); console.log(hth);
hth
는Person
의 인스턴스 이다.