본문 바로가기

Front-End/ECMAScript2015

[ES6] ECMAScript 2015 주요 기능

ECMAScript 2015 (ECMAScript 6, ES6)

ES6는 2015년에 공식적으로 업데이트 된 ECMAScript 언어의 여섯 번째 버전이다. ES6에는 클래스, 모듈, 새로운 키워드 등을 비롯해 새로운 기능이 많이 추가되었다. 최근 react.js나 node.js 프로젝트들에서는 대부분 ES6가 사용되고 있다.


그렇다면 ES6의 주요 기능에 대해 알아보자.

1. let / const

ES6에서는 변수를 선언하는 새로운 키워드로, let과 const가 추가되었다. 기존에는 var 키워드를 사용했었는데, var 키워드는 재선언과 재할당이 모두 가능했지만, let 키워드는 재할당만 가능하며, 재선언은 불가능하다. 그리고 const는 재할당과 재선언이 모두 불가능하다.


또한, var는 선언이 hoisting 되어, 선언하지 않아도 사용할 수 있었지만, let과 const는 선언 없이는 사용이 불가능하다.


var, let, const에 대한 비교는 따로 작성했다. (http://jess2.tistory.com/106?category=749446)

2. Arrow function

Arrow function(화살표 함수)은 function 키워드 대신 화살표를 사용하여 함수를 선언할 수 있다. Arrow function의 문법은 아래와 같다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 매개변수 지정 방법
    () => { ... } // 매개변수가 없을 경우
     x => { ... } // 매개변수가 한개인 경우, 소괄호를 생략할 수 있다.
(x, y) => { ... } // 매개변수가 여러개인 경우, 소괄호를 생략할 수 없다.
 
// 함수 몸체 지정 방법
=> { return x * x }  // single line block
=> x * x             // 함수 몸체가 한줄의 구문이라면 중괄호를 생략할 수 있으며 암묵적으로 return된다. 위 표현과 동일하다.
 
() => { return { a: 1 }; }
() => ({ a: 1 })  // 위 표현과 동일하다. 객체 반환시 소괄호를 사용한다.
 
() => {           // multi line block.
  const x = 10;
  return x * x;
};
cs


또한, Arrow function은 익명 함수로만 사용할 수 있기 때문에 Arrow function을 호출하기 위해서는 함수 표현식을 사용해야 한다.


1
2
let pow = x => x * x;
console.log(pow(10)); // console > 100
cs


function 키워드를 사용하여 생성한 일반 함수와 Arrow function의 가장 큰 차이점은 this이다. 일반 function 키워드를 사용한 함수일 경우, 해당 함수 호출 패턴에 따라 this에 바인딩 되는 객체가 달라진다.


하지만 Arrow function은 자신을 포함하는 외부 scope에서 this를 계승 받는다. 이것을 Lexical this라고 한다.


1
2
3
4
5
6
7
8
9
//ES5
document.getElementById("testId").addEventListener("click"function() {
    console.log(this); // console > #testId
});
 
//ES6
document.getElementById("testId").addEventListener("click", () => {
    console.log(this); // console > Window
});
cs

3. 탬플릿 리터럴(Template Literals)

ES5에서는 문자열과 변수를 함께 사용하려면 +기호를 사용하여야 했지만, ES6에서는 back-ticked(`)를 사용하여 문자열을 간단히 처리할 수 있다.


1
2
3
4
5
6
7
8
9
//ES5
var name = 'jessie';
var test1 = "My name is" + name + ". Nice to meet you."
 
//ES6
var test2 = `My name is ${name}. Nice to meet you.`
 
document.write(test1); //My name is Jessie. Nice to meet you.
document.write(test2); //My name is Jessie. Nice to meet you.
cs


3행과 6행은 방식은 다르지만 동일한 결과를 가져온다.

4. 멀티 라인 문자열(Multi-line Strings)

ES5에서는 멀티 라인 문자열을 처리하기 위해 \n과 +를 사용해야 했지만, ES6에서는 back-ticked(`)를 사용하여 간단히 처리할 수 있다.


1
2
3
4
5
6
7
8
var multi = 'this is multi line. \n'
+ 'And my name is jessie'
 
var multi2 = `This is multi line.
And my name is Jessie.`
 
alert(multi);
alert(multi2);
cs

5. Class

ES6에서는 class 키워드가 추가되었다. 기존에 프로토타입 기반으로 객체 지향 설계하는 것이 복잡하여 class라는 문법이 도입된 것이다.


1
2
3
4
5
6
7
8
9
10
11
12
class Student {
  getName() {
    document.write('jessie');
  }
  getGrade() {
    document.write(4);
  }
}
 
let student = new Student();
student.getName(); // jessie
student.getGrade(); // 4
cs


Class의 Constructor

new 연산자는 class의 constructor를 호출함과 동시에 인자들을 매개변수로 넘긴다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Student {
  constructor(name, grade) {
    this.name = name;
    this.grade = grade;
  }
  getName() {
    return this.name;
  }
}
 
let student = new Student('jessie'4);
document.write(student.name); // jessie
document.write(student.grade); // 4
document.write(student.getName()); // jessie
cs


'Front-End > ECMAScript2015' 카테고리의 다른 글

[ES6] Class  (0) 2018.05.04