익명함수를 반환할 때
- Gadget 생성자 함수의 prototype 프로퍼티는 return으로 반환되는 익명함수이다.
- g1, g2 객체의 prototype 링크는 익명함수의 prototype 객체를 먼저 찾는다.
- 익명함수의 prototype 객체는 아무 것도 return하지 않으므로 '생성자 함수가 아닌 일반 함수를 호출할 때 리턴값이 명시되어 있지 않으면 undefined가 리턴된다.'(인사이드 자바스크립트 p.110)
- 이 형태는 곧 '모든 함수들의 부모 객체인 Function.prototype'(인사이드 자바스크립트 p.88)이며 Function.prototype가 가리키는 constructor 프로퍼티는 '이 함수가 생성자로 사용될 때 이 함수를 통해 생성된 객체의 부모 역할을 하는 프로토타입 객체를 가리킨다.'(인사이드 자바스크립트 p.88)
- Function.prototype의 constructor 프로퍼티는 Object.prototype을 가리키므로 결국 g1, g2는 Object.prototype이 된다.
const Gadget = (function () {
let counter = 0;
return function () {
// 함수 코드 실행 전 빈 객체 생성
console.log((counter += 1));
};
})();
const g1 = new Gadget();
const g2 = new Gadget();
const g3 = new Gadget();
console.dir(Gadget);
console.dir(g1);
console.dir(g2);
익명함수가 아닌 기명함수 robot를 리턴할 때
const Gadget = (function () {
let counter = 0;
return function robot() {
console.log((counter += 1));
};
})();
const g1 = new Gadget();
const g2 = new Gadget();
const g3 = new Gadget();
console.dir(Gadget);
console.dir(g1);
console.dir(g2);