생성자 함수(constructor)

new 연산자와 함께 객체(인스턴스)생성하는 함수

1. Object 생성자 함수

const person = new Object();
console.log(person); // {}

//프로퍼티 추가
person.name = "lee";
person.sayHello = function () {
  console.log(`hi ` + this.name);
};
console.log(person); //{name: 'lee', sayHello: ƒ}

person.sayHello(); // hi lee

2. 생성자 함수를 쓰는 이유

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

객체를 생성할 때 객체 리터럴이 더 간편하다.

하지만 동일한 프로퍼티를 가지는 객체를 여러 개 생성하는 경우, 비효율적이다.

const 개발자1 = {
  name: "프론트엔드",
  작업() {
    console.log(this.name + ` 작업중입니다.`);
  },
};
console.log(개발자1.작업()); // 프론트엔드 작업중입니다.

const 개발자2 = {
  name: "백엔드",
  작업() {
    console.log(this.name + ` 작업중입니다.`);
  },
};
console.log(개발자2.작업()); // 백엔드 작업중입니다.

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

//생성자 함수
  function 개발자(_name) {
    this.name = _name;
    this.작업 = function () {
      console.log(this.name + " 작업중입니다.");
    };
  }
//인스턴스 생성
const 개발자1 = new 개발자("프론트엔드");
const 개발자2 = new 개발자("백엔드");

console.log(개발자1.작업()); // 프론트엔드 작업중입니다.
console.log(개발자2.작업()); // 백엔드 작업중입니다.

생성자 함수와 new 연산자만 있다면 객체 하나를 간편하게 만들 수 있다!

3. this

this는 객체 자신의 프로퍼티나 메서드를 참조하기 위한 자기 참조 변수(self-referencing variable)이다

3.1. this 바인딩

<aside> 💡

바인딩(name binding)