개발/Javascript
[ES6] 비구조화 할당, 객체 리터럴 생성 간편화
yunzema
2019. 12. 24. 14:26
반응형
1. 비구조화 할당
: 객체의 필드를 꺼내 새로운 변수를 대입하는 상황을 단순화
//ES5
var example ={
name : "james",
age: "15",
school: "some"
};
var name = example.name;
var age = example.age;
//ES6 비구조화 할당
const example ={
name : "james",
age: "15",
school: "some"
};
let {name, age} = example;
console.log(name, age); //james 15
//ES6 함수 파라미터 응용
const example ={
name : "james",
age: "15",
school: ["some", "any", "how"]
};
function printSchools ({schools}) {
schools.map((school)=>{
console.log(school);
});
}
printShools(example);
//some
//any
//how
//ES6 배열의 비구조화 할당
const language = ["java", "c", "python", "kotlin"];
const [first, second, third] = languages;
console.log(first, second, third);
//java c python
2. 객체 리터럴 생성 간편화
- 객체 생성시 프로퍼티 초기화, 메서드 정의 간편화
//ES6
const name = "홍길동";
const age = "22";
const example = {
name,
age,
getName(){ //ES5 : getName: function (){
return this.name
}
}
console.log(example); //{name:"홍길동", age:"22"}
console.log(example.getName) //홍길동