JavaScript
Arrow function in JavaScript
seoca
2019. 8. 28. 02:31
Function declaration 일반적인 함수선언
function foo() {};
Function expression 함수표현식
const foo = function(){};
Arrow function 화살표함수
const foo = () => {};
const foo = num => {}; //single parameter는 {}생략가능. ()가능. return생략가능
간단한 화살표함수의 활용
function(num){return `saved ${num}`};
//위의 내용을 arrow function을 사용하면 간단해진다
num => `saved ${num}`; //parameter가 하나고 한 줄이면 {}와 return 생략가능
*JavaScript들어가거나 multi-line string사용 할 때 ``backtick(template literal)사용.
Features of Arrow function
No function name
- It's always anonymous function
const arrow = function(){
}
const arrow = () => {
}
|
No 'this'
- bind() can not be used.
- no new
- 함수는 자기만의 'this'가 존재하지만 화살표함수는 this를 가지고 있지 않아. 그렇기에 그 함수가 포함된 함수의 'this'를 사용하게 된다.
- It can not be used as constructor. 생성자에서 this는 생성자함수로 생성된 instance가 되는데 그 this 는 존재하지 않기 때문에 화살표함수는 constructor로 쓸 수 없다.
ERROR
const arrow = () => {
}
new arrow();
|
No arguments
- argument 가 존재하지 않는다.
ERROR
const arrow = () => {
console.log(arguments);
}
arrow(1,2,3,4);
|
Arrow Function Example I
function outer(){
const arrow = () => {
console.log(arguments);
}
arrow();
}
outer(1,2,3,4);
|
output
[Arguments] { '0': 1, '1': 2, '2': 3, '3': 4 }
Arrow Function Example II
Arrow function을 사용할 때 한 문장이면 '{ }' 생략 'return' 생략
단, 매개변수가 없다면 () 필요
Example II
//1
reduce(function (a, b) {
return a + b;
});
//2
reduce((a, b) => a+b);