
자바스크립트를 사용하다 보면 객체의 속성과 메서드를 정의하는 다양한 방법을 접하게 된다. ES6+에서는 이를 더 간단하게 표현할 수 있는 문법들이 추가되었다. 이 문법들을 제대로 이해하지 못하면 코드를 읽거나 쓸 때 어려움을 겪을 수 있다.
// 이런 코드를 마주쳤을 때
const name = 'JavaScript';
const version = 'ES6';
const features = ['arrow function', 'destructuring'];
const languageInfo = {
name,
version,
features,
printInfo() {
console.log(`${this.name} ${this.version}`);
}
};
이 코드는 ES6+ 문법을 모르는 개발자에게는 다음과 같은 의문점이 생길 수 있다.
1. name : name 이렇게 해야되는거 아닌가?
2. perintInfo(){}는 함수 선언을 잘못한거 아닌가? function 키워드는 어디갔지?
이 코드를 이해하려면 ES6+의 Shorthand Property 문법을 알아야 한다.
변수명과 객체의 속성명이 같을 때 사용할 수 있는 축약 문법
// ❌ 일반적인 방식
const name = 'jun';
const age = 20;
const user = {
name: name,
age: age
};
// ✅ Shorthand Property 사용
const user = {
name, // name: name과 동일
age // age: age와 동일
};
객체의 메서드를 정의할 때 function 키워드를 생략할 수 있는 축약 문법
// ❌ 기존 방식
const person = {
firstName: 'junhee',
lastName: 'lim',
getFullName: function() {
return this.firstName + ' ' + this.lastName;
}
};
// ✅ Concise Method 사용
const person = {
firstName: 'junhee',
lastName: 'lim',
getFullName() { // function 키워드 생략
return this.firstName + ' ' + this.lastName;
}
};
const firstName = 'junhee';
const lastName = 'lim';
const age = 20;
// ✅ Shorthand Property와 Concise Method 함께 사용
const person = {
firstName, // Shorthand Property
lastName, // Shorthand Property
age, // Shorthand Property
getFullName() { // Concise Method
return `${this.firstName} ${this.lastName}`;
}
};