React는 es6 기반으로 설계되었기 때문에 es6 먼저 살펴보자.
ES6(ES2015) : ECMA라는 국제 기구에서 만든 표준문서 ECMAScript의 6번째 개정판 표준 스펙
(javascript가 다양한 브라우저에서 공통되게 작동하기 위해 만들어짐)
var : 사용 X(if,for구문에서 제한되지 않는 경우가 있어서 사용X)
let : { }
으로 블록 단위의 scope를 한정
for(let i=0; i<10; i++){} console.log(i); //not defined
const : 상수(값을 재할당이 불가능하여도 배열과 오브젝트 값을 변경하는 것은 가능)
문자열을 연결하거나 문자열 중간에 변수를 삽입하여 사용
${}
: let message = `Hello ${student.name} from ${student.city}`;
매개변수 없이 함수 호출시 default값 사용
function hello(name = 'KI', msg = 'Welcome') {
return `${msg} ${name}`;
}
console.log(hello()); // Welcome KI
function
키워드 없이 함수를 생성하고, return
을 안써도 값 자동 반환 function(name){
return name.toUpperCase();
}
name => name.toUpperCase();
name => () => console.log('hello');
const name = (name,city) => console.log('${name}'은 ${city}에 산다');
console.log(this.window); //true
let basket = {
name : "ball"
hello(){
console.log(this === window); //false
console.log(this); //basket 객체
}
}
객체를 모두 전달할 필요없이, 필요한 객체 내부의 변수만 전달
//es5
const points = [1,2,3];
const x = points[0];
const y = points[1];
const z = points[2];
console.log(x,y,z); //1,2,3
//ex6
const [x,y,z] = points;
console.log(x,y,z); //1,2,3
const [x,,z] = points;
console.log(x,z); //1,3
//ex5
const car = {
type : 'suv'
,color : 'white'
,model : x6
};
const type = car.type;
const color = car.color;
const model = car.model;
console.log(type,color,model); //suv white x6
//es6
const {type,color,model} = car;
console.log(type,color,model); //suv white x6
구조를 다시 만들어내는 과정 또는 내용을 묶는 과정
const type = 'suv'
const color = 'white'
const print = function(){
console.log('${this.type}의 ${this.color}는 2021년식 모델이다')
}
let car = {type,color,print};
myCar.print();
// ES5
var skier = {
name: name,
sound: sound,
powderYell: function() {
var yell = this.sound.toUpperCase();
console.log(yell + yell + yell + '!!!');
}
speed: function(mph) {
this.speed = mph;
console.log('속력(mph):', mph);
}
}
// ES6
let skier = {
name,
sound,
powderYell() {
let yell = this.sound.toUpperCase();
console.log(`${yell} ${yell} ${yell}!!!`);
}
speed(mph) {
this.speed = mph;
console.log('속력(mph):', mph);
}
}
...
)const points = [1,2,3];
console.log(...points); //1 2 3
const points = [1,2,3];
const counts = [4,5,6];
const sum = [...points, ...counts]; //[1,2,3,4,5,6]
let points = [1,2,3,4,5];
let [first, ...rest] = points;
console.log(rest); //2,3,4,5
function multiply(multiplier, ...theArgs) {
return theArgs.map((element) => multiplier * element);
}
let arr = multiply(2, 1, 2, 3);
console.log(arr); // [2, 4, 6]
비동기 요청에 성공이나 실패 처리를 단순화
function myAsyncFunction(url) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.onload = () => resolve(xhr.responseText);
xhr.onerror = () => reject(xhr.statusText);
xhr.send();
});
}
myAsyncFunction('https://jsonplaceholder.typicode.com/todos/1').then(
json => console.log(json),
err => console.log(new Error('조회 실패'))
)
request나 response와 같은 HTTP의 파이프라인을 구성하는 요소를 조작
fetch('https://jsonplaceholder.typicode.com/posts')
.then(function (response) {
return response.json();
})
.then(function (data) {
console.log(data);
});
클래스 선언 추가됨. 또한 extends
를 이용하여 클래스 확장(상속)
class Vacation() {
constructor(destination, length) {
this.destination = destination;
this.length = length;
}
print() {
console.log(this.destination + "은(는) " + this.length + "일 걸립니다");
}
}
const trip = new Vacation("칠레", 7);
trip.print() // 칠레은(는) 7일 걸립니다.
모듈 : 다른 js파일에서 쉽게 불러서 활용할 수 있는 재사용 가능한 코드조각
// Example.js
const a = 1;
const b = 2;
export { a };
export const c = 3;
export default b;
// Example2.js
import d, { a, c as e } from './Example';
console.log(a, d, e); // 1, 2, 3