화살표 함수는 ES6에 새로 추가된 함수 작성 방법이다. 기존 함수 표현식과 비교하면 훨씬 간결하게 사용 가능하다. 다만 두 표현식은 여러 차이점을 가지고 있기 때문에 완전 화살표 함수만으로 완전히 기존 함수 표현식을 대체할 수 있는 것은 아니다. 마찬가지로 화살표 함수를 표현식을 단순히 함수 코드를 '짧게'하기 위해 사용하는 것은 올바르지 않은 접근이다. 하지만 둘의 차이점을 잘 인지하고 사용한다면, 필요에 따라 훨씬 간결하고 가벼운 코드를 작성할 수 있다.
// 1. 화살표 함수
let difference = (a, b) => a - b;
// 2. 일반 함수 표현식
function difference(a, b) {
return a - b;
}
=>
를 기준으로 좌측 (a, b)를 매개변수로, a - b를 실행문으로 받는다.return
명령 없이도 스스로 결과값을 반환한다. 화살표 함수는 일반 함수 표현식과 다르게 본인만의 this
가 없다. 따라서 화살표 함수의 this
는 언제나 본인을 둘러싸고 있는 lexical scope 안의 다른 this
를 가리킨다.
let person1 = {
name: 'James',
age: 23,
sayHi: () => `Hi ${this.name}, you are ${this.age} years old`
}
let person2 = {
name: 'Kevin',
age: 14,
sayHi: function() {
return `Hi ${this.name}, you are ${this.age} years old`
}
}
console.log(person1.sayHi());
//output: Hi undefined, you are undefined years old
console.log(person2.sayHi());
//output: Hi Kevin, you are 14 years old
person1
의 경우 sayHi
함수가 화살표 함수 표현식으로 작성되었다. person2
와 동일하게 name 값과 age 값을 할당받았음에도 sayHi
함수를 사용해보면 두 값 모두 undefined
로 반환된다. person2
의 경우, 일반 함수 표현식만 사용했을 뿐인데 name
과 age
값 모두 제대로 반환되는 것을 확인할 수 있다. undefined
가 반환되는 것이다.this
가 없다고 표현하면 마치 단점인 것처럼 보이지만, 사실 어디서 쓰든간에 내부즤 this
값을 변화시키지 않는 점이 화살표 함수를 사용하는 가장 핵심 이유이다.
let 오브젝트1 {
함수: function() { console.log(this); }
}
console.log(오브젝트1.함수());
//output: 오브젝트1
let 오브젝트2 {
함수 : () => console.log(this)
}
console.log(오브젝트2.함수());
화살표 함수는 prototype
프로퍼티를 가지고 있지 않으므로 생성자 함수로 사용할 수 없다.
const arrFunc = () => {};
console.log(arrFunc.prototype);
//output: undefined (화살표 함수는 prototype 프로퍼티가 없다)
const arrow = new arrFunc();
//output: TypeError: arrFunc is not a constructor
화살표 함수에서는 arguments
변수가 전달되지 않는다.
function regFunc(a, b, c) {
console.log(arguments[0]);
console.log(arguments[1]);
console.log(arguments[2]);
}
regFunc(10, 20, 30); //Output: 10, 20, 30
const arrFunc = (a) => arguments[0];
console.log(arrFunc(10)); //output: {}
arguments
값이 출력되지만 화살표 함수의 경우 아무 것도 출력되지 않는다. this
, arguments
를 통해서 보이듯 화살표 함수는 함수 자체의 바인딩을 갖지 않는다.