모르는 사람들은 무지성 에로우 펑션을 사용했을것이다.
근대 다른 코드들을 보면 function을 사용한 코드들을 본적이 있을것이다
도대체 뭐가 다르길래?
비교에 앞서 알아야할 것들이 있다.
디스가 무엇인지?
그리고 메소드와 함수의 차이점을 알아보자
let a ={
b:function(){// 난 메소드 겍체에 속성값으로 담겨져있음}
}
function a(){
// 난그냥함수 전역에 선언되어있음
}
일반함수(function)
화살표함수(arrowFunction)
function ReturnFunc() {
this.name = "하이";
return {
name: "바이",
speak: function () {
console.log(this.name);
},
};
}
function ReturnArrFunc() {
this.name = "하이";
return {
name: "바이",
speak: () => {
console.log(this.name);
},
};
}
const normalFunc = new ReturnFunc();
normalFunc.speak(); // "바이"
const arrfunc = new ReturnArrFunc();
arrfunc.speak(); // "하이"
위에 코드를 비교해보면
일반함수는 자신이 속한 객체를 가르킨다.
화살표함수는 자신이 속한 인스턴스를 가르킨다.
const arr = () => {};
const func = function () {};
let a = new arr(); // error
let b = new func();
const arr = () => {
console.log(arguments);
};
const func = function () {
console.log(arguments);
};
arr(1, 2, 3); //VM275:2 Uncaught ReferenceError: arguments is not defined
// at arrFun (<anonymous>:2:15)
// at <anonymous>:1:1
func(1, 2, 3);
//Arguments(4) [1, 2, 3, 4, callee: ƒ, Symbol(Symbol.iterator): ƒ]
//0: 1
//1: 2
//2: 3
//3: 4
// ....
다음 코드를 확인해보자
console.log(x()); // x 함수 선언문 호이스팅가능
function x() {
return "x";
}
console.log(xx()); //ReferenceError: Cannot access 'xx' before initialization
// 함수 표현식은 호이스팅 불가능
const xx = function () {
return "xx";
};
//위와같은 특성때문에 화살표함수는 호이스팅이 불가능하다.
// 표현식이 불가능한 이유는 형태를 보면 알수있듯이 변수로 선언취급되어 선언부만 끓어올림