new 연산자와 함께
객체(인스턴스)
를 생성
하는 함수
String
, Number
, Boolean
, Function
, Array
, Date
, RegExp
, Promise
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
객체를 생성할 때 객체 리터럴이 더 간편하다.
하지만 동일한 프로퍼티를 가지는 객체를 여러 개 생성하는 경우, 비효율적이다.
const 개발자1 = {
name: "프론트엔드",
작업() {
console.log(this.name + ` 작업중입니다.`);
},
};
console.log(개발자1.작업()); // 프론트엔드 작업중입니다.
const 개발자2 = {
name: "백엔드",
작업() {
console.log(this.name + ` 작업중입니다.`);
},
};
console.log(개발자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 연산자만 있다면 객체 하나를 간편하게 만들 수 있다!
this
는 객체 자신의 프로퍼티나 메서드를 참조하기 위한 자기 참조 변수
(self-referencing variable)이다
<aside> 💡
바인딩이란
, 식별자와 값을 연결하는 과정을 의미한다.
this와 this가 가리킬 객체를 바인딩하는 것.