Web/javascript

함수 선언식과 함수 표현식 그리고 화살표 함수

rockettttman 2021. 8. 2. 16:30

함수 선언식 - Function Declarations

function test() {
return 'function declarations'
}
test();

함수 표현식 - Function Expressions

var test = function () {
return 'function expressions';
}
test();

두 방식의 차이점

  • 함수 선언식은 호이스팅에 영향을 받지만, 함수 표현식은 호이스팅에 영향을 받지 않는다.
console.log(test()) //@@@@ 정상 출력
console.log(test2()) // undefined 뜨고 TypeError 발생(TypeError: test2 is not a function)
function test() {
console.log('@@@@')
}
var test2 = function() {
console.log('#####')
}
  • 함수 표현식은 closure로 사용 가능하다.
  • 함수 표현식은 콜백으로 사용할 수 있다. javascript array 함수 중 callback으로 리턴받아 처리하는 함수들이 있다. map 함수 등등

화살표 함수 - Arrow Function

var test= () => function() {
return 'arrow function'
}
test();

기본적으로 함수 표현식처럼 hoisting이 허용되지 않으며 함수 선언부보다 빠르게 호출할 시 TypeError가 발생한다.

함수 표현식과 화살표 함수의 차이점

  • 보통 arrow함수의 특징처럼 this가 바라보는 곳이 다르다. 일반 함수 선언부와 같은 경우는 Window 객체를 바라보지만 arrow 함수의 this는 그 객체를 바라본다.
  • arguments 변수가 정의되어 있지 않다.
const f = () => console.log(arguments);
f(); // ReferenceError: arguments is not defined
function g() {
console.log(arguments)
}
g(); //[Arguments] {}
const h = function () {
console.log(arguments)
}
h(); //[Arguments] {}
  • 생성자로 사용할 수 없다.
const Person = (name, age) => { this.name = name; this.age = age };
const tom = new Person("Tom", 18); // Person is not a constructor
  • yield를 사용할 수 없다.