function & arrow function

최정환·2022년 11월 5일
0

JS 문법 따로따로 

목록 보기
3/4

들어가며

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 ;
  1. 코드의 양

    function이라는 표현식이 없어도 함수로 정의가 가능하기 때문에 코드의 양이 줄어든다.
    소괄호와 중괄호가 생략 가능하다.

  2. 암시적 return

    return이 없어도 값 반환이 가능하다.


내부 차이점

this가 가르키는 값

ES6에서의 this는 Lexical this다.

가장 중요한 점은 함수 안에서 arguments 바인딩이다.

일반 함수는 가장 가까운 부모 함수의 arguments 객체에 접근이 가능하지만
화살표 함수에는 arguments 바인딩이 없다.

  • 일반 함수
    일반 함수 안에서 this의 값은 동적이며 동적 context의 값이 함수가 호출되는 방식에 따라 달라진다.
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
  • 화살표 함수
    화살표 함수는 자체 실행 context를 정의하지 않기 때문에 this값은 정적이다.
    항상 상위 스코프의 this를 가르킨다. > Lexical this
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

Constructor

화살표 함수는 prototype가 존재하지 않는다.

  • 일반 함수
    일반 함수는 객체(instance)를 쉽게 생성 가능하다.
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

Hoisting

호이스팅이란

함수 선언문: 어디서든 호출 가능
함수 표현식: 함수를 초기화한 코드 아래에서만 호출가능

// 선언문
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;

Closure

화살표 함수를 사용한다면 클로저를 좀 더 간단하게 선언, 사용이 가능하다.

// 일반
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

0개의 댓글