화살표 함수는 ES6에 도입되었다.
화살표 함수를 사용하면 더 짧게 함수 구문을 작성할 수 있다.
let myFunction = (a, b) => a * b;
hello = function() {
return "Hello World!";
}
hello = () => {
return "Hello World!";
}
짧아진다! 함수에 명령문이 하나만 있고 명령문이 값을 반환하는 경우 대괄호와 return 키워드를 제거(생략)할 수 있다.
참고: 이는 함수에 명령문이 하나만 있는 경우에만 작동한다.
hello = (val) => "Hello " + val;
hello = val => "Hello " + val;
this
를 처리하는 방법도 일반 함수와 비교해보면 화살표 함수에서는 다르다.
요컨대, 화살표 기능에는 this
대한 바인딩이 없다.
일반 함수에서 this
키워드는 함수를 호출한 객체를 나타낸다. 이 객체는 window, 문서(document), 버튼 또는 무엇이든 될 수 있다.
화살표 함수에서 this
키워드는 항상 화살표 함수를 정의한 객체를 나타낸다.
차이점을 이해하기 위해 두 가지 예시를 살펴보자.
두 예시 모두 페이지가 로드될 때
, 먼저 메서드를 한 번 호출하고 사용자가 버튼을 클릭할 때
, 다시 한 번 메서드를 호출하여 총 두 번 호출한다.
첫 번째 예시는 일반 함수를 사용하고 두 번째 예는 화살표 함수를 사용한다.
결과는 window 객체가 함수의 "owner"이기 때문에 첫 번째 예시는 두 개의 다른 객체(window and button)를 반환
하고 두 번째 예시는 window 객체를 두 번 반환
함을 보여준다.
this
는 함수를 호출하는 객체를 나타낸다.<!DOCTYPE html>
<html>
<body>
<h2>JavaScript "this"</h2>
<p>This example demonstrate that in a regular function, the "this" keyword represents different objects depending on how the function was called.</p>
<p>Click the button to execute the "hello" function again, and you will see that this time "this" represents the button object.</p>
<button id="btn">Click Me!</button>
<p id="demo"></p>
<script>
var hello;
hello = function() {
document.getElementById("demo").innerHTML += this;
}
//The window object calls the function:
window.addEventListener("load", hello);
//A button object calls the function:
document.getElementById("btn").addEventListener("click", hello);
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript "this"</h2>
<p>This example demonstrate that in Arrow Functions, the "this" keyword represents the object that owns the function, no matter who calls the function.</p>
<p>Click the button to execute the "hello" function again, and you will see that "this" still represents the window object.</p>
<button id="btn">Click Me!</button>
<p id="demo"></p>
<script>
var hello;
hello = () => {
document.getElementById("demo").innerHTML += this;
}
//The window object calls the function:
window.addEventListener("load", hello);
//A button object calls the function:
document.getElementById("btn").addEventListener("click", hello);
</script>
</body>
</html>
함수로 작업할 때 이러한 차이점을 기억하자. 때로는 일반 함수의 동작이 우리가 원하는 것이지만, 그렇지 않은 경우 화살표 함수를 사용하자.