객체의 프로퍼티를 간결하게 표현하는 방식(ES2015)
축약형 표현이 가능한 경우
객체를 만들 때 변수에 할당된 값으로 프로퍼티를 만들 수 있는데 , 변수 이름과 프로퍼티 네임이 같다면 축약 가능.
const title = 'codeit';
const birth = 2017;
const job = '프로그래밍 감사';
const user = {
title: title,
birth: birth,
job: job,
};
const user = {
title,
birth,
job,
};
마찬가지로 외부에 있는 함수를 메소드로 만들 때도 함수명이 같다면 함수명()과 콜론 지우기로 축약이 가능하다.
객체 내부에서 선언한 메서드는 콜론과 function() 키워드 생략 하면 된다.
const user = {
firstName: 'Test',
lastName: 'Jang',
getFullName: function(){ //객체 내부에서 메서드선언
return `${this.firstName} ${this.lastName}`;
}
}
console.log(user.getFullName());
const user = {
firstName: 'Test',
lastName: 'Jang',
getFullName() { //생략
return `${this.firstName} ${this.lastName}`;
}
}
console.log(user.getFullName());
계산된 속성명(computed property name)
표현식을 대괄호로 감싸면 표현식의 값을 프로퍼티 네임으로 쓸 수 있음
객체의 프로퍼티는 표현식이 가지는 값을 통해 점 표기법으로 접근하거나, 표현식을 그대로 사용해서 대괄호 표기법으로 접근할 수 있다.
표현식으로 프로퍼티 네임을 나타내기
const propertyName = 'birth';
const getJob = () => 'job';
const codeit = {
['topic' + 'Name']: 'Modern JavaScript',
[propertyName]: 2017,
[getJob()]: '프로그래밍 강사',
};
console.log(codeit.topicName) //Modern JavaScript
console.log(codeit[propertyName]) //2017
console.log(codeit[getJob()]) //프로그래밍 강사
console.log(codeit.job) //프로그래밍 강사
console.log(codeit.birth) //2017
문제
const user = {
name: 'codeit',
birth: 2017,
() => {
const date = new Date();
return date.getFullYear() - this.birth + 1;
},
};
위 코드는 문제가 있다.
1. Arrow Function을 호출할 이름이 없기 때문이다. 따라서 이름을 붙여줘야 한다.
2. Arrow Function안에서 this키워드는 window객체를 가리켜서 코드의 의도와는 다르게 동작한다.
3. 일반적으로 객체의 메소드를 만들 땐 일반 함수가 좀 더 권장된다.
옵셔널 체이닝(Optional Chaining)
- ECMAScript2020
- 중첩된 객체의 프로퍼티에 접근하는 방법
- 옵셔널 체이닝 연산자(?.)
- 왼편의 프로퍼티 값이 undefined또는 null이 아니라면 그다음 프로퍼티 값을 리턴하고 그렇지 않은 경우 undefined를 리턴하는 문법
//동작원리를 삼항 연산자로 표현
(user.cat === null || user.cat === undefined) ? undefined : user.cat.name)
등장 배경
function printCatName(user) {
console.log(user.cat.name);
}
const user1 = {
name: 'Captain',
cat: {
name: 'Crew',
breed: 'British Shorthair',
}
}
printCatName(user1); // Crew
중첩된 객체를 다룰 때, 예상한 프로퍼티를 가지고 있지 않을 수도 있다.
const user2 = {
name: 'Young',
}
console.log(user2.cat); // undefined
printCatName(user2); // TypeError: Cannot read property 'name' of undefined
따라서 중첩된 객체의 프로퍼티를 다룰 때는 접근하기 전에 null 혹은 undefined가 아니라는 것을
검증하고 접근해야 에러를 방지할 수 있다.
function printCatName(user) {
console.log(user.cat && user.cat.name);
}
if문을 활용할 수 있지만 간결하게 AND연산자를 활용했었지만 객체의 이름이나 프로퍼티의 이름이 길어질수록
가독성이 나빠지는 문제가 있었다. 이런 상황에서 더 간결하게 사용할 수 있다.
function printCatName(user) {
console.log(user.cat?.name);
}
null 병합 연산자 + 옵셔널 체이닝 연산자
function printCatName(user) {
console.log(user.cat?.name ?? '함께 지내는 고양이가 없습니다.');
}
const user2 = {
name: 'Young',
}
printCatName(user2); // 함께 지내는 고양이가 없습니다.
널 병합 연산자 - a가 undefined 또는 null이 아니라면 a, 그 외의 경우는 b
옵셔널 체이닝 - a가 undefined 또는 null이 아니라면 그다음 프로퍼티 값, 그 외의 경우 undefined
'[코드잇] > JavaScript 백엔드 개발자' 카테고리의 다른 글
모던 자바스크립트 - Destructuring(구조 분해) With 객체 (0) | 2023.02.25 |
---|---|
모던 자바스크립트 - Destructuring(구조 분해) With 배열 (0) | 2023.02.25 |
모던 자바스크립트 -Spread구문- (0) | 2023.02.24 |
모던자바스크립트 -문장/표현식/조건연산자- (0) | 2023.02.24 |
모던 자바스크립트 -Arrow Function, this- (0) | 2023.02.22 |