-
모던 자바스크립트 Deep Dive - 생성자 함수에 의한 객체 생성JavaScript 2021. 9. 16. 19:02
keyword = [ 생성자 함수 , 일반 함수 , 내부 메서드 , Call , Construct , new.target ]
Object 생성자 함수
new 연산자와 함께 Object 생성자 함수를 호출하면 빈 객체를 생성하여 반환한다.
const person = new Object(); console.log(person); // { } person.name = 'Kim'; person.sayHello = function(){ console.log('Hi ! My name is ' + this.name); }; console.log(person); // { name : 'Kim' , sayHello : f } person.sayHello(); // Hi! My name is Kim
생성자 함수 : new 연산자와 함께 호출하여 객체를 생성하는 함수를 말한다.
생성자 함수에 의해 생성된 객체를 인스턴스 라 한다.특별한 이유가 존재하지 않는다면 유용하지 않다.
생성자 함수
객체 리터럴에 의한 객체 생성 방식은 동일한 프로퍼티를 갖는 객체를 여러개 생성해야하는 경우 비효율적이다.
// 객체 리터럴 사용 const circle1 = { radius : 5, getDiameter(){ return 2 * this.radius; } }; const circle2 = { radius : 10, getDiameter(){ return 2 * this.radius; } } // 생성자 함수 사용 function Circle(radius){ this.radius = radius; this.getDiameter = function(){ return 2 * this.radius; }; } const circle1 = new Circle(5); const circle2 = new Circle(10);
[ 생성자 함수의 인스턴스 생성 과정 ]
function Circle(radius){ this.radius = radius; this.getDiameter = function(){ return 2 * this.radius; }; }
위 코드는 자바스크립트 엔진에 의하여 아래와 같이 동작한다.
function Circle(radius){ this = {} this.radius = radius; this.getDiameter = function(){ return 2 * this.radius; }; return this; }
[ 내부 메서드 [[Call]] 과 [[ Construct]] ]
함수는 객체이지만 일반 객체와는 다르다.
일반 객체는 호출할 수 없지만, 함수는 호출할 수 있다.
함수로 동작하기 위하여 내부 슬롯과 내부 메서드( [[Call]] , [[Construct]] )를 추가로 가지고 있기 때문이다.function foo(){} // 일반적인 함수 : [[Call]] 호출 foo() // 생성자 함수 : [[Construct]] 호출 new foo();
그럼 함수가 일반 함수로 작동하는지 ? 생성자 함수로 작동하는지 ? 가 궁금할 것이다.
정답은 new 연산자를 함께 사용하느냐 마느냐 이다.[ constructor와 non-constructor ]
모든 함수 객체는 [[Call]]을 갖고 있지만,
모든 함수 객체는 [[Construct]]를 갖고있지는 않다.[[Construct]]를 가지고있는 함수를 constructor ( 함수 선언문 , 함수 표현식 , 클래스 )
[[Construct]]를 가지고있지 않는 함수를 non-constructor라 한다. ( 화살표 함수 , 메서드 (함수를 프로퍼티 키값으로 사용) )// 일반 함수 function foo(){} const bar = function () {}; const baz = { x : function(){} }; new foo(); new bar(); new baz.x(); // 화살표 함수 const arrow = () => {} new arrow(); // TypeError // 메서드 정의 const obj = { x(){} } new obj.x() // TypeError
[ new.target ]
new.target을 사용하여 생성자 함수로 호출되었는지 확인할 수 있다.
일반 함수로 호출한 경우 new.target 값은 undefined이다.function Circle(radius){ if(!new.target){ return new Circle(radius); } this.radius = radius; this.getDiameter = function(){ return 2 * this.radius; }; }
'JavaScript' 카테고리의 다른 글
모던 자바스크립트 Deep Dive - 프로토타입 (0) 2021.09.16 모던 자바스크립트 Deep Dive - 함수와 일급 객체 (0) 2021.09.16 모던 자바스크립트 Deep Dive - 프로퍼티 어트리뷰트 (0) 2021.09.16 모던 자바스크립트 Deep Dive - let, const 키워드와 블록 레벨 스코프 (0) 2021.09.16 모던 자바스크립트 Deep Dive - 전역 변수의 문제점 (0) 2021.09.16