es2015 요약
ES2015
ES2015는 Javascript의 버전이다. Ecma라는 단체에서 기존의 결점을 보완한 표준 자바스크립트 버전을 매년 발표한다. ES는 EcamaScript의 줄임말이다.
let
- 블록 스코프 변수(block scoped variable)이다.
- var가 함수 스코프 변수 이라는 점에서 대비된다.
- 블록 단위안에서도 hoisting 되지 않는다.
- 같은 스코프에서 재선언이 불가능하다.
ex:
- 블록 스코프 변수 / 함수 스코프 변수 예제
if(true) {var a = 'a';let b = 'b';console.log('a => ', a); // aconsole.log('b => ', b); // b}console.log('a => ', a); // aconsole.log('b => ', b); // b is not defined
- hoisting 예제
if(true) {console.log('a => ', a); // undefinedconsole.log('b => ', b); // b is not definedvar a = 'a';let b = 'b';}
- 같은 스코프에서 재선언 불가능 예제
var a = 'a'; // a = 'a'var a = 'aa'; // a = 'aa'let b = 'b'; // b = 'b'let b = 'bb'; // Identifier 'b' has already been declared
const
- 읽기 전용 상수
- 객체를 할당하면 참조값이 상수에 할당되므로 객체의 프로퍼티는 변경 가능
- const 또한 block scoping을 따르며 hoisting 되지 않는다.
ex:
- 읽기 전용 예제
const a = 'a'; // a = 'a'a = 'b' // Assignment to constant variable.
- 프로퍼티 변경 예제
const a = {name: 'a'};console.log('a.name => ', a.name); // aa.name = 'b';console.log('a.name => ', a.name); // b
Set - Collection
- Set은 유일한 값들로 구성된 Collection
- add한 순서대로 원소를 가지고 있다.
- 중복된 값은 자동 삭제된다.
ex:
const a = new Set();a.add(1).add(2).add(1); // Set {1, 2}console.log('a size: ', a.size); // 2a.delete(2); // Set {1}a.forEach(f => console.log(f)); // 1WeakSet - Collection
- weakly하게 값을 참조한다는 뜻인데 WeakSet이 갖는 객체의 참조값이 다른곳에서 참조되지 않으면 객체는 garbage collect 대상
- 객체 참조값만 가진다.
- iterable 객체가 아니다.
- .has(), .get(), .set(), .delete()만 지원
ex:
const ws = new WeakSet();const value = {a: 'a'};ws.add(value).add({b: 'moon'});console.log(ws); // WeakSet {Object {b: "moon"}, Object {a: "a"}}/* after the garbage Collection has run */console.log(ws); // WeakSet {Object {a: "a"}}Map - Collection
- key-value로 이루어진 Collection
- iterable 객체
- 삽입한 순서대로 원소를 가진다.
ex:
const map = new Map();const obj = {a: 2};map.set(obj, 2).set(1, 1).set(1, 2);console.log('map has 1: ', map.has(1)); // map has 1: trueconsole.log('value of 1: ', map.get(1)); // value of 1: 2map.delete(1);console.log('map has 1: ', map.has(1)); // map has 1: falseWeakMap - Collection
- WeakSet 과 비슷한 개념으WeakMap 의 key 가 약하게 참조된다.
- key는 객체참조 값만을가진다.
- iterable 객체가 아니다.
ex:
const ws = new WeakMap();const obj = {a: 'a'};ws.set(obj, 1).set({b: 2}, 2);console.log(ws); // WeakMap {Object {a: "a"} => 1, Object {b: 2} => 2}/* after the garbage Collection has run */console.log(ws); // WeakMap {Object {a: "a"} => 1}arrow function
- 보다 간결한 구문을 지닌 익명함수이다.
- 자기 고유의 this 를 갖지 않고, 외부 스코프의 this 를 그대로 가진다 (lexical binding)
ex:
const func = (x, y) => { return x + y; };/* json을 리턴할 때에는 괄호를 넣어준다. */const func2 = () => ({ foo: 1 });class
- 기존모델에 단지 새롭게 추가된 구문일 뿐,전혀 새로운 객체지향 모델이 아니다.
- 생성자나 상속의 좀 더 간단하고 명확한 구문이 제공된다.
- 생성자는 constructor 로 표현된다.
- 클래스 바디는 중괄호 안에 두고 여기에 메소드를 function 키워드 없이 정의한다.
- 메소드는 prototype 프로퍼티에 추가된다.
- class는 프로퍼티와 메소드로 이루어져 있다.
- class 는 extends 구문으로 다른 class 를 상속한다.
- 자식 클래스에 constructor 가 없으면 부모의 그것이 자동으로 호출된다.
- 생성자에서 super 키워드를 통해 상속 계층을 구현한다. this 보다 먼저 사용하지 않으면 예외가 발생한다.
- static 키워드를 통해 정적 메소드를 만들 수 있다. 이 메소드는 클래스 prototype 프로퍼티가 아닌 클래스 자체 메소드 다. (유틀리티 함수 작성에 쓰인다.)
ex:
- 일반 예제
class Point {constructor(x, y) {this.x = x;this.y = y;}static distance(a, b) {const dx = a.x - b.x;const dy = a.y - b.y;return Math.sqrt(dx*dx + dy*dy);}}const p1 = new Point(5, 5);const p2 = new Point(10, 10);console.log(Point.distance(p1, p2)); // 7.0710678118654755
- 상속
class Cat {constructor(name) {this.name = name;}speak() {console.log(this.name + ' makes a noise.');}}class Lion extends Cat {speak() {super.speak();console.log(this.name + ' roars.');}}const lion = new Lion('happy');lion.speak();
Template string
- 백틱(Backtick)을 이용해 문자열을 만드는 새로운 방법
- 코드의 가독성을 높여준다.
- ${} 표현식을 사용하여 변수, 함수, 연산식 등을 표현 할 수 있다.
ex:
const name = 'dowon';const myStr = `Hi ${name}. Have a great day!`;console.log(myStr); // Hi dowon. Have a great day!console.log("string text line 1\n"+"string text line 2");/* "string text line 1 string text line 2" */console.log(`string text line 1string text line 2`);/* "string text line 1 string text line 2" */const a = 5;const b = 10;console.log(`Fifteen is ${a + b} and not ${2 * a + b}.`); // Fifteen is 15 and not 20.const a = () => "test";console.log(`a: => ${a()}`);for~of 구문
- for~in 문은 객체의 열거가능한 모든 속성에 대해 반복했다면, for ~ of 문은 컬렉션의 요소를 반복.
- forEach(), for in 구문과 달리, break, continue, 그리고 return 구문과 함께 사용할 수 있습니다.
- for~of 루프 구문은 data를 순회하기 위한 구문
- 배열 뿐만 아니라 Collection 객체, DOM NodeList 등등 을 다를수 있다.
ex)
for (let chr of "12") {console.log(chr);}//1//2let iterable = [10, 20, 30];for (let value of iterable) { console.log(value);}let iterable = new Uint8Array([0x00, 0xff]);for (let value of iterable) { console.log(value);}// 0// 255let iterable = new Map([["a", 1], ["b", 2], ["c", 3]]);for (let entry of iterable) { console.log(entry);}// [a, 1]// [b, 2]// [c, 3]for (let [key, value] of iterable) { console.log(value);}// 1// 2// 3let iterable = new Set([1, 1, 2, 2, 3, 3]);for (let value of iterable) { console.log(value);}// 1// 2// 3Iterator
- Iterator 는 새로운 문법이나 built-in 이 아니라 프로토콜(약속)이다.
- 간단한 약속만 지키면 누구나 만들수 있다.
- Set Map Array 등이 Iterator 객체이다.
- Symbol.iterator 를 Key 로 갖는 속성이 반드시 존재해야 한다.
- 다음 규칙에 따라 next() 메서드를 구현한 객체를 iterator 라고 한다:
아래의 두 속성을 가지는 객체를 리턴하며 인자가 없는 함수:1. done (boolean) - iterator 가 순회를 모두 마쳤을 경우 true - iterator 가 순회할 다음 value 가 존재할 경우 false2. value - iterator 에 의해 리턴될 값. done 이 true 일 경우 생략 가능ex:
var iterable = { [Symbol.iterator]() { return { i: 0, next() { if (this.i < 3) { return { value: this.i++, done: false }; } return { value: undefined, done: true }; } }; }};for (var value of iterable) { console.log(value);}// 0// 1// 2Rest Parameter 와 Default Parameter
이건 코드로 확인하는게 가장 편하다.
-
rest parameter
// 사용법은 아래와 같다.function(a, b, ...theArgs) {// ...}// exfunction restParam(...arg) {for(let val of arg) console.log(val);}restParam(1,2,3,4,5);// es2function restParam2(first, ...arg) {console.log(first); // 시작for(let val of arg) console.log(val);// 1// 2// 3// 4// 5}restParam('시작', 1,2,3,4,5); -
Default Parameter
- parameter 값이 없을 시 Default로 값을 넣어준다.
function defaultParam(a = 'test', b = 'done') {console.log(`a: ${a}`);console.log(`b: ${b}`);}defaultParam();//
기타
const obj = {a:1, b:2};const {a,b} = obj;console.log(a,b); // 12const a = [1,2,3];const aCopy = [...a];console.log(aCopy);