답은 공식문서에 있을거다라는 생각으로 w3c먼저 들어가 보니
https://www.w3schools.com/js/js_es6.asp 에 잘 정리 되어 있다.
영어로..
그러니 그냥 한글로 정리하기
ES6에서 변수 선언하기 위한 키워드가 추가 됐다.
기존 var의 경우 호이스팅 되는 현상이 있어 이를 보완하기 위해 나왔다고 한다.
const
let
코드를 더 읽기 쉽고, 더 체계적이고, 최신코드처럼 보이게 한다.
//ES5
fucntion test(a) {
return a + '님';
}
console.log(test('병우')); // 병우님
//ES6
const test = (a) => {
return `${a}님`;
// 화살표 함수는 함수 내부의 내용이 반환값(return)만 있다면 return과 중괄효{}를 생략해도 된다.
}
//const test = (a) => `${a}님`;
console.log(test('병우'));// 병우님
//ES5
var address = {
country: 'South Korea',
city : 'Seoul',
street: 'Gangnam',
str_num: 141,
postcode:'00510',
}
//ES6
const { country, city, street, str_num, postcode } = address;
ES5의 경우 사용 하려면 address.country 처럼 써야하지만
ES6의 경우 country만 써도 사용 가능하다.
//ES5
function getAddress(country, city, street) {
var myAddress = {
country: country,
city: city,
street: street,
str_num:888,
postcode: '9999'
};
}
getAddress('Korea','Seoul','Euncheon');
//ES6
function getAddress(country, city, street) {
const myAddress = {
country,
city,
street ,
str_num:888,
postcode: '9999'
};
}
getAddress('Korea','Seoul','Euncheon');
매개변수와 객체프로퍼티 이름이 같다면 생략 가능
country: country -> country
많은 for문이 있다. for ~ in, forEach, for() 등등
그러나 각 key 값이나 value 값만 추출되거나 break문을 사용하지 못해 사용 권장 하지 않으므로 추가 됐다고 한다.
for(let year of years){
console.log(year);
if(year == 2001){
break;
}
// 2001
}
for ~ of의 경우 배열의 내용을 출력할 수 있고 내부에서 break문 사용 가능하다.
...(점 3개)를 사용하여 배열, 객체, 문자열을 다른 배열, 객체, 문자열과 결합하기 위해 사용한다.
let coffee = ['black', 'latte']
let coffee2 = ['레스비', '맥심']
const 음료 = [...coffee, ...coffee2]
console.log(음료) // ['black', 'latte','레스비', '맥심']
//es6
const foo = (a, b = "b", c = "c") => {
console.log(a, b, c);
};
foo("a");
//a b c
파라미터에 기본값을 설정할 수 있다. 따라서 별도 지정하지 않을 경우 기본값이 출력 된다.
const myArray = [1, 2, 3, 4, 5, 5 ,5 ,5 ,5];
const mySet = new Set(myArray);
console.log(myArray) // [1, 2, 3, 4, 5, 5 ,5 ,5 ,5] 배열
console.log(mySet)// {1, 2, 3, 4, 5} 집합
Set는 배열과 유사한 순회 가능한 객체이다.
배열처럼 value로만 이뤄져있지만, 값이 키와 동일하게 설정되어있다.
값은 중복될 수 없으며, 중복될 경우 가장 앞의 값을 제외하고 삭제된다
Map은 Object와 상당히 유사한 순회 가능한 객체이다.
[key, value]의 형태로 이뤄져있으며, 선언하거나 추가시 이러한 형태로 값을 넣어주어야한다.
length가 아닌 size로 Map 값의 크기를 알 수 있다.
promise는 자바스크립트 비동기 처리에 사용 되는 객체이다.
비동기란 '특정코드의 실행이 완료될 때까지 기다리지 않고 다음 코드를 먼저 수행하는 자바스크립트의 특성'
API요청 후 데이터를 받아오기도 전에 마치 데이터를 다 받아온 것 마냥 화면에 데이터를 표시하려고 하면 오류가 발생하거나 빈 화면이 나타난다.
이와 같은 문제를 해결하기 위한 방법이 비동기통신이다.
pending(대기): 비동기 처리 로직이 아직 완료되지 않은 상태
Fulfilled(이행): 비동기 처리가 완료되어 프로미스가 결과값을 반환해준 상태
Rejected(실패): 비동기 처리가 실패하거나 오류가 발생한 상태
function getData() {
return new Promise(function(resolve, reject) {
var data = 100;
resolve(data); // 이행 상태
});
}
getData().then(function(resolvedData) {
console.log(resolvedData); // 100
});
이행상태가 되면 아래 then()을 이용하여 처리 결과 값을 받을 수 있다.
function getData() {
return new Promise(function(resolve, reject) {
reject(new Error("Request is failed"));
});
}
// reject()의 결과 값 Error를 err에 받음
getData().then().catch(function(err) {
console.log(err); // Error: Request is failed
});
실패 상태가 되면 실패 이유를 catch()로 받을 수 있다.
//기존 문자열 출력 방식
let data = 1234
let desc = 'data is '
console.log(desc + data)
//변경
let data = 1234
let desc = `data is ${data}, ${data * 3}`
console.log(desc)
//클래스 사용 방법
class Building {
constructor(width, height) {
this.width = width
this.height = height
}
log(){ //function을 생략하고 함수를 사용
console.log(this.width, this.height)
}
static print(num){ //static 함수
console.log(num)
}
}
let apt = new Building(100, 200)
console.log(apt.width, apt.height) //100, 200
Building.print(200) //200 -> 오류 발생 : apt.print(200)
//////////////////////////////////////////////////
//상속받아 사용하는 방법
class Apart extends Building { //상위클래스의 생성자를 구현해야 함.
constructor(width, height) {
this.width = width
this.height = height
}
//log, print 함수를 지니고 있음.
}
let apt2 = new Apart(100, 200)
console.log(apt2.width, apt2.height) //100, 200
Apart.print(200)
클래스라는 기능은 1개의 영역 안에 다양한 함수, 변수 등을 집어넣고 사용 할 수 있게 해주는 기능 입니다.
클래스는 new 연산자를 통해서 생성 할 수 있으며, 호이스팅이 되지 않으므로 유의하여야 합니다.
클래스에서 함수는 function을 제거하고 선언 합니다.
클래스에서 static 함수는 new로 생성된 변수에서 접근하는 것이 아니라 클래스에서 바로 접근해야 합니다.
클래스는 다른 클래스를 상속 받아서 기존 클래스의 기능을 이어받을 수 있습니다.
export, import 를 통해 나누어서 개발된 파일(*.js)간의 관계를 유지하여 줍니다.
js파일에서 전달할 기능은 export, 사용하는 곳에서는 import를 선언하여 서로의 위치를 참조하게 합니다.
기존에 html파일에서
promise, let/const, modules, class, spread operator, 구조분해할당, 기본 매개변수, 화살표 함수, 반복문for of, 템플릿 리터럴 등..