Programming/Javascript
[Javascript] ES6 화살표(에로우) 함수
cbw1030
2019. 3. 27. 19:55
반응형
1. ES6에서는 화살표 기호를 사용하여 화살표 함수를 만들 수 있다.
화살표 함수를 사용하는 방법에는 몇 가지 제약이 따른다.
// 1) 매개변수가 없는 경우
const area = () => { return 100; };
// 2) 매개변수가 한 개인 경우, 이 때는 () 괄호를 생략할 수 있다.
const area = width => { return width; };
const area = (width) => { return width; };
// 3) 매개변수가 두 개 이상인 경우. 이 때는 () 괄호를 생략할 수 없다.
const area = (width, height) => { return width * height ;};
// 4) 함수 몸체가 한 줄의 구문이라면 {}를 생략할 수 있으며 암묵적으로 return이 적용된다.
const area = (width, height) => { return width * height; };
const area = (width, height) => width * height;
// 5) 함수 몸체가 여러 줄의 구문이라면 {}, return을 생략할 수 없다.
const area = (width, height) => {
const result = width * height;
return result;
};
// 6) 객체를 반환할 때는 소괄호를 사용한다.
const area = () => { return { width: 100, heigth: 200 }; };
const area = () => ( { width: 100, height: 200 } );
2. 화살표 함수는 익명 함수로만 생성 가능하다.
// ES5
var area = function (width, height) { return width * height; };
// ES6
const area = (width, height) => width * height;
// 만약 콜백 함수로 사용할 경우 이전보다 간결하게 표현할 수 있다.
var arr = [1, 2, 3];
// ES5
var pow = arr.map(function(x) { return x * x });
// ES6
const pow = arr.map(x => x * x);
3. 화살표 함수는 자신만의 this를 생성하지 않고 자신을 포함하고 있는 상위 context로부터 this를 상속 받는다.
이를 Lexical this라고 한다.
function Greeting(greet) {
this.greet = greet;
}
Greeting.prototype.name = function (arr) {
return arr.map(x => {
console.log(this);
return `${this.greet} ${x}`
});
};
const greet = new Greeting('Hi');
const arr = ['Lee', 'Kim'];
console.log(greet.name(arr));
4. 화살표 함수의 스코프에는 arguments가 들어있지 않다.
const myFun = () => {
console.log(arguments);
}
myFun(1, 2, 3, 4) // Uncaught ReferenceError : arguments is not defined
하지만 rest parameter을 이용하면 arguments가 아닌 진짜 배열을 이용할 수도 있다.
const myFun = (...args) => {
console.log(args)
}
myFunc(1, 2, 3, 4) // [1, 2, 3, 4] (유사배열이 아닌 진짜 배열)
p.s. 네이버 블로그 기발자님의 화살표함수 포스팅과 유튜버 코드님의 동영상을 참고했습니다.
티스토리가 업데이트를 해서 그런지 코드블록에 색상이 안들어가네요.
반응형