CH17 생성자 함수에 의한 객체 생성

liz·2023년 3월 16일
0

17.1 Object 생성자 함수

new 연산자와 함꼐 Object 생성자 함수를 호출하면 빈 객체를 생성해 반환한다..

//빈객체 생성
const person = new Object();

//프로퍼티 추가
person.name = 'Lee';
person.sayHello = function () {
    console.log('Hi! My name is ' + this.name);
};

console.log(person); // {name: 'Lee', sayHello: f}
person.sayHello(); // Hi! My name is Lee

생성자 함수(constructor)란 new 연산자와 함께 호출하여 객체(인스턴스)를 생성하는 함수를 말한다. 생성자 함수에 의해 생성된 객체를 인스턴스라 한다

c.f 생성자 함수 = 붕어빵틀
인스턴스 = 붕어빵 틀로 찍어낸 붕어빵

  • 자바스크립트는 Object 생성자 함수 이외에도 String, Number, Boolean, Function, Array, Date, RegExp, Promise 등의 빌트인 함수를 제공한다.
const strObj = new String('Lee'); //String
const numObj = new Number(123); //Number
const boolObj = new Boolean(true); //Boolean
const func = new Function('x', 'return x * x'); //Function
const arr = new Array(1, 2, 3); //Array 객체(배열)
const regExp = new RegExp(/ab+c/i); //정규표현식
const date = new Date();

console.log(typeof strObj, numObj,); //object
console.log(strObj, numObj);

console.log(typeof func); //function
console.log(func);

17.2 생성자함수

17.2.1 객체 리터럴에 의한 생성 방식의 문제점

객체 리터럴에 의한 생성 방식은 직관적이고 간편하하다
하지만, 한 번에 단 하나의 객체만 생성하기에 동일한 프로퍼티를 갖는 객체를 여러 개 생성해야 하는 경우 매번 써줘야 돼서 비효율적이다.

17.2.2 생성자 함수에 의한 객체 생성 방식의 장점

17.2.3 생성자 함수의 인스턴스 생성 과정

1. 인스턴스 생성과 this 바인딩

2. 인스턴스 초기화

3. 인스턴스 반환

17.2.4 내부 메서드 [[call]]과 [[construct]]

17.2.5 constructor와 non-constructor의 구분

17.2.6 new 연산자

17.2.7 new.target

profile
프론트엔드 개발자 준비중

0개의 댓글