화살표 함수(Arrow function)은 자바스크립트의 ES6버전의 특징 중 하나이다. 화살표 함수는 기존의 function을 만드는 것에 비해 깔끔하게 함수를 만들 수 있다.
// 기존의 함수
let x = function(x,y){
return x*y;
}
// 화살표 함수
let x = (x,y)=> x*y;
}
기본 구문
let myFunction = (arg1, arg2, ...argN) => { statement(s) }
// 화살표 함수의 body에 하나의 statement 또는 expression만 있는 경우 중괄호{}를 생략해도 된다. let myFunction = (arg1, arg2, ...argN) => expression
// 매개변수가 하나뿐인 경우 괄호는 선택사항 let x = (x)=> x*10; }
// 매개변수가 하나뿐인 경우 괄호는 선택사항 let x = x=> x*10; }
- 매개변수가 하나뿐인 경우
// 매개변수가 없으면 괄호는 필수 let greet = () => console.log('Hello'); greet(); // Hello }
- 매개변수가 없는 경우
화살표 함수는 자신의 this가 없다. 대신 화살표 함수는 자신을 둘러싸는 렉시컬 범위의 this가 사용된다.
function Person() { this.name = 'Jack', this.age = 25, this.sayName = function () { console.log(this.age); function innerFunc() { // this refers to the global object console.log(this.age); console.log(this); } innerFunc(); } } let x = new Person(); x.sayName();
output
25
undefined
window {}
this.sayName()안에 있는 this.age는 접근할 수 있지만, innerFunc()는 일반 함수이기 때문에 this.age에는 접근이 불가능하다. 왜냐하면 this는 global object인 Window object를 참조하고 있기 때문이다.function Person() { this.name = 'Jack', this.age = 25, this.sayName = function () { console.log(this.age); let innerFunc = () => { console.log(this.age); } innerFunc(); } } const x = new Person(); x.sayName();
output
25
25
반면에 위의 코드는 this.sayName() 함수 안에서 화살표 함수를 사용했다. 화살표함수는 부모 범위의 this를 참조하고있기 때문에 this.age는 25를 출력한다.