2022년 11월 5일
이론JS
조회 : 304|1분 읽기

function & arrow function

들어가며

JS에서 모든 함수는 Function 객체이다. 그러므로 다른 모든 객체와 같이 속성, 메서드를 가질 수 있으므로 일급 객체이다.

글을 작성하는 이유

화살표 함수는 ES6에 나온 신문법으로 function을 완전히 대체하기 위해 나온 문법은 아니다.
하지만 둘은 분명한 차이점이 그저 코드를 이쁘고 짧게 작성할 수 있어서 사용하는 것만이 아니기 때문에 차이점을 분명히 알기 위해 작성한다.

제일 먼저 보이는 코드의 간결함

javascript
1function add(x, y) {
2  return x + y;
3};
4// ES6 arrow function
5let add = (x, y) =>  x + y ;
6let sqrt = x => x*x ;
  1. 코드의 양
    function이라는 표현식이 없어도 함수로 정의가 가능하기 때문에 코드의 양이 줄어든다. 소괄호와 중괄호가 생략 가능하다.
  2. 암시적 return
    return이 없어도 값 반환이 가능하다.

내부 차이점

this가 가르키는 값

ES6에서의 this는 Lexical this다.
가장 중요한 점은 함수 안에서 arguments 바인딩이다.
일반 함수는 가장 가까운 부모 함수의 arguments 객체에 접근이 가능하지만 화살표 함수에는 arguments 바인딩이 없다.
  • 일반 함수 일반 함수 안에서 this의 값은 동적이며 동적 context의 값이 함수가 호출되는 방식에 따라 달라진다.
javascript
1const object {
2	method() {
3      console.log(this);
4    }
5  showArg(){
6      console.log(arguments); 
7  }
8};
9
10const outB = {
11	b: 12,
12	show: function show(){console.log(this.b)}
13}
14
15object.method(); // object를 보여준다.
16object.showArg(1,2,3,4) // 1,2,3,4
17outB.show(); // 12
  • 화살표 함수
화살표 함수는 자체 실행 context를 정의하지 않기 때문에 this값은 정적이다.
항상 상위 스코프의 this를 가르킨다. > Lexical this
javascript
1const object = {
2	method(items){
3    	console.log(this) // object를 보여준다.
4      const callback = ()=>{
5	    console.log(this) // object를 보여준다.
6      };
7    };
8  
9  showArg:()=> {
10    console.log(...arguments)
11  }
12}
13
14const outB = {
15	b: 12,
16	show: ()=> console.log(this.b)
17}
18
19object.showArg(1,2,3) // error arguments not defined
20new meme() // error meme is not constructor
21outB.show() // undifined

Constructor

화살표 함수는 prototype가 존재하지 않는다.
  • 일반 함수
일반 함수는 객체(instance)를 쉽게 생성 가능하다.
javascript
1function Animal(name){
2	this.name = name
3}
4const Dog = new Animal('dog');
5Dog instanceof Animal // true
  • 화살표 함수
javascript
1const Animal = name => 	this.name = name;
2
3const Dog = new Animal('dog');
4Dog instanceof Animal // error Animal is not a constructor

Hoisting

함수 선언문: 어디서든 호출 가능
함수 표현식: 함수를 초기화한 코드 아래에서만 호출가능
javascript
1// 선언문
2function say(){
3	console.log("hi")
4}
5// 표현식
6const say = function () {
7	console.log("hi")
8}
  • 기명 함수 : 함수 선언문, 호이스팅 가능
javascript
1add(1,2) // 3
2
3function add(a,b){
4	return a+b
5} 
  • 익명 함수, 화살표 함수 : 함수 표현식, 호이스팅 불가능
javascript
1add(1,2)	// error add not defined
2const add = function (a,b){return a+b}
3
4plus(1,2)  // error plus not defined
5const plus = (a,b) => a+b;

Closure

화살표 함수를 사용한다면 클로저를 좀 더 간단하게 선언, 사용이 가능하다.
javascript
1// 일반
2function a(x){
3  let y = x+1;
4	return function b() {
5		return x+y
6    }
7}
8
9a(1)() // 3
10
11// 화살표
12const add = x => {
13	let y = x+1;
14  return () => x+y
15}
16
17add(1)() // 3