객체 리터럴을 사용하면 객체를 쉽게 만들 수 있으나, 유사한 객체를 여러개 만들어야할 때 불편한 점이 있습니다.
이 때 new 연산자와 생성자 함수를 사용하면 유사한 객체를 쉽게 만들 수 있습니다.
function User(first, last) {
// this는 빈 객체를 의미합니다.
// 암시적으로 빈 객체를 생성합니다.
// 새로운 프로퍼티를 this에 추가합니다.
this.firstName = first;
this.lastName = last;
// return this; -> this가 암시적으로 반환됩니다.
}
// 로직이 똑같기 때문에 메모리를 좀 더 효율적으로 관리할 수 있습니다.
// 숨겨진 prototype 속성에 getFullName을 할당해서 메모리에 한 번만 만들어집니다.
User.prototype.getFullName = function () {
return `${this.firstName} ${this.lastName}`;
};
const ji = new User("ji seok", "yu");
const gildong = new User("gil dong", "hong");
console.log(ji.getFullName()); // gil dong hong
console.log(gildong.getFullName()); // ji seok yu
❗ 생성자 함수를 사용하면 재사용이 가능한 객체 생성 코드를 작성할 수 있습니다.
일반 함수에서 this와 화살표 함수에서의 this는 차이를 갖습니다.
// 객체 리터럴 this
const ji = {
name: "Ji",
normal() {
console.log(this.name);
},
arrow: () => {
// 함수가 선언된 부분에서 정확하게 무엇을 지칭하는지 불분명합니다. -> name undefined
console.log(this.name);
},
};
ji.normal(); // Ji -> 함수가 호출되는 위치 즉 this 값이 ji 객체로 정의됩니다.
ji.arrow(); // undefined
// 생성자 함수 this
function Person(name) {
this.name = name;
}
Person.prototype.normal = function () {
console.log(this.name);
};
Person.prototype.arrow = () => {
// 선언된 함수 범위에서 this를 찾습니다.
console.log(this.name);
};
const seokji = new Person("seokji");
seokji.normal(); // seokji 일반 함수, 호출 위치에서 this가 정의됩니다. -> this = seokji
seokji.arrow(); // undefined
// 타이머 일반 함수 this
const timer = {
name: "ji",
timeout() {
setTimeout(function () { // setTimeout 내부에서 일반 함수가 호출 되어서 this.name을 찾을 수 없습니다.
console.log(this.name);
}, 3000);
},
};
timer.timeout(); // undefined -> 일반 함수는 호출 위치에서 this가 정의 되어서
// 타이머 화살표 함수 this
const timer = {
name: "ji",
function () { // 선언된 함수 범위 내에 this는 timer라는 객체 데이터를 나타냅니다.
setTimeout(() => {
console.log(this.name);
}, 3000);
},
};
timer.timeout(); // ji
❗ 타이머 함수의 콜백 함수는 화살표 함수로 사용하는 것이 활용도가 높습니다.
자바스크립트는 프로토 타입기반의 프로그래밍 언어입니다. 좀 더 안정적인 객체 지향 언어들의 영향을 받아 ES6부터 class 문법이 등장하였습니다.
class는 쉽게 붕어빵 틀을 new 연산자로 만들어진 인스턴스는 붕어빵을 생각하면 쉽습니다.
class Person {
// 내부 함수
constructor(first, last) {
this.firstName = first;
this.lastName = last;
}
// 프로토타입 메서드 지정
getFullName() {
return `${this.firstName} ${this.lastName}`;
}
}
const jiseok = new Person("jiseok", "yu");
console.log(jiseok); // Person {firstName: 'jiseok', lastName: 'yu'}
console.log(jiseok.getFullName()); // jiseok yu
❗ 앞서 살펴본 생성자 함수를 class 문법으로 작성하면 가독성이 높고 모던한 코드를 작성할 수 있습니다.
클래스 상속을 사용하면 클래스를 다른 클래스로 확장할 수 있습니다.
// 상속
class Bicycle extends Vehicle {
constructor(name, wheel) {
super(name, wheel);
}
}
const myBicycle = new Bicycle("BMX", 2);
console.log(myBicycle.name);
console.log(myBicycle.wheel);
// 상속 + 확장
class Car extends Vehicle {
constructor(name, wheel, license) {
super(name, wheel);
this.license = license;
}
}
const benz = new Car("지바겐", 4, true);
console.log(benz); // Car {name: '지바겐', wheel: 4, license: true}
console.log(benz.license); // true
붕어빵 예시가 쏙쏙 들어오네요🐟
깔끔한 정리 오늘도 잘 보고갑니다🙌🏻