이번 시간에는 ES6에서 쓰이는 문법을 정리해보겠습니다.
ES5의 형태를 먼저 보고 ES6에서는 어떻게 쓰이는지를 비교해가면서 살펴보겠습니다.
//ES5
var john = ["john", 26];
var name = john[0];
var age = john[1];
//ES6
const [name, year] = ["john", 26];
console.log(name);
console.log(year);
////////////////////////////////////////////////////////////////////////////
const obj = {
name: "heeje",
age: 25,
};
const { name: n, age: a } = obj; // 새로운 이름을 할당해 줄 수도 있다.
console.log(n);
////////////////////////////////////////////////////////////////////////////
function calcRetire(year) {
const age = new Date().getFullYear() - year;
return [age, 60 - age]; //배열을 return
}
const [age2, retirement] = calcRetire(1996); //destructuring
console.log(age2);
console.log(retirement);
const boxes = document.querySelectorAll(".box"); //node list return
//ES5
var boxesArr5 = Array.prototype.slice.call(boxes);
boxesArr5.forEach(function (cur) {
cur.style.backgroundColor = "dodgerblue";
});
const boxesArr6 = Array.from(boxes); //from 을 사용해서 쉽게 들고 올 수 있다.
boxesArr6.forEach((cur) => (cur.style.backgroundColor = "dodgerblue")); // arrow function.
//ES5
for (var i = 0; i < boxesArr5.length; i++) {
if (boxesArr5[i].className === "box blue") {
continue;
} else {
boxesArr5[i].textContent = "blue!";
}
}
//ES6
for (const cur of boxesArr6) { //for of loop (간단하게 쓸 수 있다.)
if (cur.className.includes("blue")) {
continue;
} else {
cur.textContent = "blue";
}
}
////////////////index 접근//////////////////////////
//ES5
var ages = [12, 13, 23, 15, 25, 17];
var full = ages.map(function (cur) {
return cur >= 18;
});
console.log(full.indexOf(true)); // 조건에 맞는 인덱스를 반환
console.log(ages[full.indexOf(true)]); // 조건에 맞는 인덱스를 가진 배열 값 반환.
//ES6
console.log(ages.findIndex((cur) => cur >= 18));
console.log(ages.find((cur) => cur >= 18));
function add(a, b, c, d) {
return a + b + c + d;
}
//ES5
var ages = [20, 20, 30, 30];
var sum1 = add.apply(null, ages);
console.log(sum1);
//ES6
let sum2 = add(...ages); /// '...' 의 형태로 배열의 모든 원소에 접근할 수 있다.
console.log(sum2);
const familySmith = ["John", "Jane", "Mark"];
const familyMiller = ["Mary", "Bob", "Ann"];
const bigFamily = [...familySmith, "Lily", ...familyMiller]; //spread operator 를 통해서 간단하게 배열울 합칠 수 있다.
console.log(bigFamily);
//ES6
function isFullAge6(limit, ...years) { // ...years 가 rest parameters 로 자동으로 인식된다.
years.forEach(cur => console.log( (2016 - cur) >= limit));
}
isFullAge6(16, 1990, 1999, 1965, 2016, 1987);
➡️ spread operator 랑 구별 필요!
// ES5
function SmithPerson(firstName, yearOfBirth, lastName, nationality) {
lastName === undefined ? lastName = 'Smith' : lastName = lastName;
nationality === undefined ? nationality = 'american' : nationality = nationality;
this.firstName = firstName;
this.lastName = lastName;
this.yearOfBirth = yearOfBirth;
this.nationality = nationality;
}
//ES6
function SmithPerson(firstName, yearOfBirth, lastName = 'Smith', nationality = 'american') { //parameter 의 default 값을 미리 설정해줄 수 있다.
this.firstName = firstName;
this.lastName = lastName;
this.yearOfBirth = yearOfBirth;
this.nationality = nationality;
} // 그리고 값이 들어오면 덮어 쓴다.
var john = new SmithPerson('John', 1990);
var emily = new SmithPerson('Emily', 1983, 'Diaz', 'spanish');
new Map()
– 새로운 맵 생성.map.set(key, value)
– key
를 이용해 value
를 저장map.get(key)
– key
에 해당하는 값을 반환. key
가 존재하지 않으면 undefined
를 반환합map.has(key)
– key
가 존재하면 true
, 존재하지 않으면 false
를 반환map.delete(key)
– key
에 해당하는 값을 삭제map.clear()
– 맵 안의 모든 요소를 제거map.size
– 요소의 개수를 반환map.keys()
– 각 요소의 키를 모은 반복 가능한(iterable, 이터러블) 객체를 반환map.values()
– 각 요소의 값을 모은 이터러블 객체를 반환map.entries()
– 요소의 [키, 값]
을 한 쌍으로 하는 이터러블 객체를 반환. 이 이터러블 객체는 for..of
반복문의 기초로 쓰인다.let map = new Map();
//key, value
map.set('1', 'str1'); // 문자형 키
map.set(1, 'num1'); // 숫자형 키
map.set(true, 'bool1'); // 불린형 키
alert( map.get(1) ); // 'num1'
alert( map.get('1') ); // 'str1'
alert( map.size ); // 3
:arrow_right: 맵은 객체를 키로 사용할 수 있다.
let john = { name: "John" };
// 고객의 가게 방문 횟수를 세본다고 가정해 봅시다.
let visitsCountMap = new Map();
// john을 맵의 키로 사용하겠습니다.
visitsCountMap.set(john, 123);
alert( visitsCountMap.get(john) ); // 123
// [키, 값] 쌍을 대상으로 순회
for (let entry of recipeMap) { // recipeMap.entries()와 동일
alert(entry); // cucumber,500 ...
}
for (let [key, value] of question.entries()) {
if (typeof(key) === 'number') {
console.log(`Answer ${key}: ${value}`);
}
}
class MyClass {
constructor() { ... } // 객체를 초기화 해주는 constructor
method1() { ... }
method2() { ... }
method3() { ... }
...
}
ex)
class Person {
constructor(name, birth, job) {
this.name = name;
this.birth = birth;
this.job = job;
}
cal() {
let age = new Date().getFullYear() - this.birth;
console.log(age);
}
}
const heeje = new Person("heeje", 1996, "student");
heeje.cal();
class athlete extends Person { //Person을 상속 받는다.
constructor(name, birth, job, game, medal) {
super(name, birth, job); // 부모 class 부르고 인자 전달.
this.game = game;
this.medal = medal;
}
wonMedal() {
this.medal++;
console.log(this.medal);
}
}
const Athlete6 = new athlete("heeje", 1996, "student", 7, 77); // new 를 통해서 새로운 object 생성.
Athlete6.wonMedal();
Athlete6.cal(); // 부모의 method 사용가능하다.
class User {
constructor(name) {
// setter를 활성화
this.name = name;
}
get name() { //getter
return this._name;
}
set name(value) { // name 과 동일하게 적어야함.
if (value.length < 4) {
alert("이름이 너무 짧습니다.");
return;
}
this._name = value;
}
}
let user = new User("John");
alert(user.name); // John
user = new User(""); // 이름이 너무 짧습니다.