ES6

ECMAScript 란?

ECMAScript is a standard script language

자바스크립트 언어의 표준입니다.

히스토리

넷스케이프에서 자바스크립트를 지원하면서 자바스크립트가 성공하자 마이크로소프트가 J스크립트를 개발했습니다. 넷스케이프는 표준화를 위해 자바스크립트 기술 규격을 ECMA 인터내셔널에 제출하였고 ECMA-262라는 표준이 생겨났습니다. 넷스케이프의 Brendan Eich가 JavaScript를 개발하였으며 Javascript는 처음에는 Mocha 라는 이름으로 후에는 LiveScript 최종적으로 Javascript라는 이름이 됐습니다.

ECMAScript 6 는 2015년 6월에 업데이트 되었습니다 ! ECMAScript의 6번째 에디션입니다.

ES6 Features

Classes

Class 문법을 제공합니다. constructor 메소드도 사용할 수 있고 extends를 통해서 클래스 상속도 가능합니다.

class Person {
    constructor (id, name) {
        this.id = id
        this.name = name
    }
    toString() {
        return (${this.id}, ${this.name})
    }
}

class Student extends Person {
    constructor (id, name, age) {
        super(id, name)
        this.age = age
    }
    toString() {
        return super.toString() + ' and ' + this.age
    }
}

let & const

const

 const schoolName = "ABC"

 schoolName = "CBA"  // Error

let

 function test() {
  let x = "a"
  if (true) {
    let x = "b"
    console.log(x);  // b
  }
  console.log(x);  // a
}

Arrow Functions

함수는 간결해지고 코드는 짧아졌습니다.

 const squares = [1, 2, 3].map(x => x * x) // 1, 4, 9

Arrow Function 은 자신만의 this를 생성하지 않습니다.

function NumberEx() {
    var that = this
    that.num = 0;
    setInterval(function add() {
        // setInterval 안에서의 this 는 NumberEx의 this가 아니므로 다른 변수에 this 를 지정하여 씁니다.
        that.num++;
        console.log(that.num);
  }, 1000);
}

화살표 함수는 자신의 this가 바인드 되지 않기 때문에 함수의 스코프에서의 this 가 적용됩니다.

function NumberEx() {
  this.num = 0

  setInterval(() => {
    this.num++ // this is from NumberEx
  }, 1000)
}

Modules

Export, Import 를 이용해 function이나 variables 들을 다른 곳에서 사용할 수 있습니다.

//  utility.js
export const squares = (arr) => { return arr.map(x => x * x) }

// math.js
import { squares } from "utility"
console.log(squares([1,2,3])) // [1,4,9]

Promises

비동기 프로세싱을 위해 사용됩니다. (Asynchronously)
가독성이 좋으며 중첩된 콜백의 단점을 완화합니다.
(Callback Hell이라는 Callback 함수가 다시 Callback을 호출하고 또다시 Callback을 호출하는 코드를 읽기도 관리하기도 힘들어지는 것은 완화할 수 있습니다.)

callback

Promise의 세가지 상태

var promiseTest = (num) => {
    return new Promise((resolve, reject) => {
        if (num > 3) {
            resolve(num)
        } else {
            reject("err")
        }
    }
}

promiseTest(5)
    .then(val => console.log(val)) // 5
    .catch(err => console.log(err))

참고링크