JS에서 모든 함수는 Function 객체이다.
그러므로 다른 모든 객체와 같이 속성, 메서드를 가질 수 있으므로 일급 객체이다.
화살표 함수는 ES6에 나온 신문법으로 function을 완전히 대체하기 위해 나온 문법은 아니다.
하지만 둘은 분명한 차이점이 그저 코드를 이쁘고 짧게 작성할 수 있어서 사용하는 것만이 아니기 때문에 차이점을 분명히 알기 위해 작성한다.
function add(x, y) {
return x + y;
};
// ES6 arrow function
let add = (x, y) => x + y ;
let sqrt = x => x*x ;
코드의 양
function이라는 표현식이 없어도 함수로 정의가 가능하기 때문에 코드의 양이 줄어든다.
소괄호와 중괄호가 생략 가능하다.
암시적 return
return이 없어도 값 반환이 가능하다.
ES6에서의 this는 Lexical this다.
가장 중요한 점은 함수 안에서 arguments 바인딩이다.
일반 함수는 가장 가까운 부모 함수의 arguments 객체에 접근이 가능하지만
화살표 함수에는 arguments 바인딩이 없다.
const object {
method() {
console.log(this);
}
showArg(){
console.log(arguments);
}
};
const outB = {
b: 12,
show: function show(){console.log(this.b)}
}
object.method(); // object를 보여준다.
object.showArg(1,2,3,4) // 1,2,3,4
outB.show(); // 12
const object = {
method(items){
console.log(this) // object를 보여준다.
const callback = ()=>{
console.log(this) // object를 보여준다.
};
};
showArg:()=> {
console.log(...arguments)
}
}
const outB = {
b: 12,
show: ()=> console.log(this.b)
}
object.showArg(1,2,3) // error arguments not defined
new meme() // error meme is not constructor
outB.show() // undifined
화살표 함수는 prototype가 존재하지 않는다.
function Animal(name){
this.name = name
}
const Dog = new Animal('dog');
Dog instanceof Animal // true
const Animal = name => this.name = name;
const Dog = new Animal('dog');
Dog instanceof Animal // error Animal is not a constructor
함수 선언문: 어디서든 호출 가능
함수 표현식: 함수를 초기화한 코드 아래에서만 호출가능
// 선언문
function say(){
console.log("hi")
}
// 표현식
const say = function () {
console.log("hi")
}
add(1,2) // 3
function add(a,b){
return a+b
}
add(1,2) // error add not defined
const add = function (a,b){return a+b}
plus(1,2) // error plus not defined
const plus = (a,b) => a+b;
화살표 함수를 사용한다면 클로저를 좀 더 간단하게 선언, 사용이 가능하다.
// 일반
function a(x){
let y = x+1;
return function b() {
return x+y
}
}
a(1)() // 3
// 화살표
const add = x => {
let y = x+1;
return () => x+y
}
add(1)() // 3
참고 :
https://dmitripavlutin.com/differences-between-arrow-and-regular-functions/
https://betterprogramming.pub/difference-between-regular-functions-and-arrow-functions-f65639aba256
https://www.youtube.com/watch?v=LPEwb5plEoU&list=LL&index=1&t=647s