-
리액트를 다시 공부하면서 생소한 문법(화살표문법 같은?)이 적응이 안되서 ES6 문법에 대해 정리를 해보았다. (모두는 아니고 배운 내용 일부만!)
1. ES6
- ECMAScript 표준의 가장 최신 버전으로 ECMAScript 6 ( ECMAScript 2015 )를 줄인 말이다.
- ES6는 새로운 언어 기능이 포함된 주요 업데이트이며, 2009년도에 표준화된 ES5 이후로 언어 기능에 대한 첫 업데이트다.
2. 추가된 기능
- arrows
- classes
- enhanced object literals
- template strings
- destructuring
- default + rest + spread
- let + const
- iterators + for ... of
- generators
- unicode
- modules
- module loaders
- map + set + weakmap + weakset
- proxies
- symbols
- subclassable built-ins
- promicses
- math + number + string + array + object APIs
- binary and octal literals
- reflect api
- tail calls
2.1 화살표 함수
- 화살표 기호 => 를 사용하여 함수를 선언.
var x = function(x, y) { return x * y; } // 화살표 함수로 표현 const x = (x, y) => x * y;
2.2 클래스
- 기존 자바스크립트 문법은 클래스 표현식이 없었지만 ES6는 클래스를 정의하여 사용할 수 있다.
-
class
키워드로 클래스를 정의할 수 있고 클래스 내에 생성자(constructor()
)도 항상 포함되어 있어야 한다.// 자동차의 이름과 연도에 대한 정보를 담는 클래스 class Car { constructor(name, year) { this.name = name; this.year = year; } } // 클래스 객체 생성 let myCar1 = new Car("Ford", 2014); let myCar2 = new Car("Audi", 2019);
2.3 forEach() 함수
- forEach() 함수를 사용하면 반복문의 순번과 배열의 크기를 따로 변수에 저장하는 과정을 생략할 수 있다.
- 구조 분해 할당 방식(키를 넣어주면 키값을 반환)
var fruits = ["apple", "orange", "cherry"]; // 배열의 각 요소를 반복문 forEach()를 이용해 접근 fruits.forEach(myFunction); // myFunction은 인덱스와 이이템을 출력하는 함수 function myFunction(item, index) { document.write(index + ":" + item + "<br>"); } // for 문 사용시 for (i=0; i<3; i++){ document.write(i); document.write(":" + fruits[i] + "<br>"); } // 실행 결과 // 0:apple // 1:orange // 2:cherry
2.4 map() 함수
- 각 배열 요소를 정의된 함수를 통해 변환한 결과값들로 새 배열을 반환.
var persons = [ {firstname : "Malcom", lastname: "Reynolds"}, {firstname : "Harry", lastname: "Kim"}, {firstname : "Pika", lastname: "Chu"} ]; function getFullName(item){ var fullname = item.firstname + " " + item.lastname; return fullname; } document.write(persons.map(getFullName)); // 실행 결과 // Malcom Reynolds,Harry Kim,Pika Chu
// 예제 2 var numbers = [1, 4, 9, 16]; var x = numbers.map(Math.sqrt) document.write(x); // 실행 결과 // 1,2,3,4
2.5 reduce() 함수
- 배열의 각 요소에 대해 주어진 함수를 실행한 후, 하나의 결과값을 반환
- map이 배열의 각 요소를 변형한다면, reduce는 배열 자체를 변형한다.
- 예를 들어, 배열에 들어있는 숫자를 더하거나 평균을 구하는 것을 배열을 값 하나로 줄이는 동작이다.
// 배열.reduce((누적값, 현잿값, 인덱스, 요소) => { return 결과 }, 초기값); var numbers = [175, 50, 15]; document.write(numbers.reduce(myFunc)); function myFunc(total, num) { return total - num; } // 실행 결과 // 115 // 이유 : (175, 50) -> (125, 10) -> 115 의 순으로 실행이 된다.
2.6 Modules
- JavaScript 모듈 로더들(AMD, CommonJS)의 패턴을 적용
- 묵시적 비동기 형태로 요구되는 모듈들이 정상적으로 로드되기 전까지 코드가 실행되지 않는다.
// lib/math.js export function sum(x, y) { return x + y; } export var pi = 3.141593; // app.js import * as math from "lib/math"; console.log(math.sum(pi, pi)); // 6.283186 console.log(math.pi); // 3.141593
export default
와export *
문법도 제공한다.// module1.js export default function test() { console.log('module1 test'); } export function test1(){ console.log('module1 test1'); } export function test2(){ console.log('module1 test2'); } // 또는 이렇게도 가능하다. function test() { console.log('module1 test'); } function test1(){ console.log('module1 test1'); } function test2(){ console.log('module1 test2'); } export default test; export {test1, test2};
// main.js import test from './module1.js'; // export default로 내보낸 것은 하나의 변수로 받아서 사용할 수 있다. // test를 받아올 때 이름을 원하는대로 지어도 된다. import f1 from './module1.js'; // 반면 export는 객체 형태이기 때문에 object destructing을 활용하여 접근이 가능하다. import {test1, test2} from './module1.js'; // export로 내보내는 이름과 동일해야 하지만 as를 사용해 별칭을 붙여줄 수 있다. import {test1 as t1, test2 as t2} from './module1.js';
그런데 만약 module1.js에 export로 내보내는 함수가 100개(test1, test2, ..., test100)라 가정해보자.
그렇다면 import 할때 엄청나게 길어지게 될 것이다.
이러한 반복을 방지하기 위해 다음과 같은 문법을 사용할 수 있다.
// main.js import * as module1 from './module1.js'; //호출하는 방법 module1.test1(); module1.test50(); module1.test100();
2.7 Binary and Octal
- 2진법 (b), 8진법 (o) numeric 리터럴 형식이 추가되었다.
0b111110111 === 503 // true 0o767 === 503 // true
'자바스크립트' 카테고리의 다른 글
코딩의 기술 4. 조건문을 깔끔하게 작성하라 (0) 2021.05.22 코딩의 기술 2. 배열로 데이터 컬렉션을 관리하라 (0) 2021.05.14 코딩의기술 1.1 const로 변하지 않는 값을 표현하라 (0) 2021.05.01 자바스크립트 객체지향 프로그래밍 (0) 2021.04.07 자바스크립트 데이터 타입과 연산자(1) (0) 2021.04.02