PROGRAMING/React

[React] 화살표 함수 (Arrow Functions)

donghunl 2024. 4. 18. 16:00
반응형

화살표 함수(Arrow Funcions)

Arrow 함수는 함수를 작성할때 좀 더 간결하게 해줄수 있는 함수입니다. 

 

기본

바로 예제를 통해 확인해 보겠습니다.

// Before
hello = function() {
  return "Hello World!";
}

// With Arrow Function
hello = () => {
  return "Hello World!";
}

 

간결해 졌습니다. 함수에 지정문이 하나만 있고 바로 그 값을 반환 한다면 아래와 같이 더 간결하게 만들수 있습니다.

// Arrow Funtions Return Value by Default
// Note: This works only if the function has only one statement.
hello = () => "Hello World!";

 

변수가 있을 경우

이번에는 매개변수가 있을 경우를 예제를 통해 확인해 보겠습니다.

// Arrow Function With Parameters
hello = (val) => "Hello " + val;

// In fact, if you have only one parameter, you can skip the parentheses as well
// Arrow Function Without Parentheses
hello = val => "Hello " + val;

변수가 하나일경우에는 괄호까지 생략을 할수 있습니다.

 

몇가지 예제를 더 확인해 보겠습니다.

// 예시 1
const sum = (a, b) => a + b;
/* 위 화살표 함수는 아래 함수의 축약 버전입니다.
const sum = function(a, b) {
  return a + b;
};
*/

alert( sum(1, 2) ); // 3

// 예시 2
const double = n => n * 2;
// const double = function(n) { return n * 2 }과 거의 동일합니다.

alert( double(3) ); // 6

위와 같이 좀더 함수를 간결하게 표현할수 있습니다.

 

동적함수의 경우

좀더 동적인 함수의 예제를 살펴보겠습니다.

// With Regular Function
function ask(question, yes, no) {
  if (confirm(question)) yes()
  else no();
}

ask(
  "동의하십니까?",
  function() { alert("동의하셨습니다."); },
  function() { alert("취소 버튼을 누르셨습니다."); }
);

// With Arrow Function
function ask(question, yes, no) {
  if (confirm(question)) yes()
  else no();
}

ask(
  "동의하십니까?",
  () => alert("동의하셨습니다."),
  () => alert("취소 버튼을 누르셨습니다.")
);

위와 같이 동적인 함수도 간결하게 표현할수 있습니다.

 

본문이 여러줄인 경우

마지막으로 본문이 여러줄 일 경우도 예시를 통해 확인해 보겠습니다.

const sum = (a, b) => {  // 중괄호는 본문 여러 줄로 구성되어 있음을 알려줍니다.
  const result = a + b;
  return result; // 중괄호를 사용했다면, return 지시자로 결괏값을 반환해주어야 합니다.
};

alert( sum(1, 2) ); // 3

위의 예시처럼 본문이 여러줄일 경우는 중괄호 안에 코드를 넣어주고 반드시 명시적으로 return 지시자를 사용하여 결과값을 반환 시켜줘야 합니다.

 

화살표 함수를 처음 접하면 가독성이 떨어질수 있습니다. 하지만 문법이 눈에 익기 시작하면 금방 적응하실수 있습니다.

함수 본문이 한줄인 간단한 함수는 화살표 함수를 사용해서 만드는게 편리 합니다. 타이핑을 적게 해도 함수를 만들수 있다는 장점이 있습니다.

 

* 한가지 this 키워드에 대해 기능이 다릅니다.

Regular 함수에서의 this 키워드는 함수를 호출한 객체를 나타냅니다. 이 객체(object) 는 Window, document, button등이 될수 있습니다.

Arrow 함수의 경우 this 키워드는 항상 화살표 함수를 정의한 객체(object)를 나타냅니다.

차이점을 이해하기 위해 두 가지 예를 살펴보겠습니다.
두 예 모두 처음에는 페이지가 로드될 때 메소드를 두 번 호출하고, 사용자가 버튼을 클릭할 때 다시 한 번 메서드를 호출합니다.
첫 번째 예는 정규 함수를 사용하고 두 번째 예는 화살표 함수를 사용합니다.
결과는 첫 번째 예에서 두 개의 서로 다른 개체(창과 단추)를 반환하고 두 번째 예에서 헤더 개체를 두 번 반환하는 것을 보여줍니다.

// 예시 1 Regular 함수
// With a regular function, this represents the object that called the function
// 로딩 : object Object
// 버튼 클릭 : object HTMLButtonElement
class Header {
  constructor() {
    this.color = "Red";
  }

//Regular function:
  changeColor = function() {
    document.getElementById("demo").innerHTML += this;
  }
}

const myheader = new Header();

//The window object calls the function:
window.addEventListener("load", myheader.changeColor);

//A button object calls the function:
document.getElementById("btn").addEventListener("click", myheader.changeColor);


// 예시 2 Arrow 함수
// With an arrow function, this represents the Header object no matter who called the function
// 로딩 : object Object
// 버튼 클릭 : object Object
class Header {
  constructor() {
    this.color = "Red";
  }

//Arrow function:
  changeColor = () => {
    document.getElementById("demo").innerHTML += this;
  }
}

const myheader = new Header();


//The window object calls the function:
window.addEventListener("load", myheader.changeColor);

//A button object calls the function:
document.getElementById("btn").addEventListener("click", myheader.changeColor);

함수를 사용할 때 이러한 차이점을 기억하세요. 때로는 규칙적인 함수의 동작이 화살표 함수를 사용하기를 원할 때도 있습니다.

반응형

'PROGRAMING > React' 카테고리의 다른 글

[React] Ternary operators  (60) 2024.04.25
[REACT] Simple shopping cart  (1) 2024.03.07
[REACT] Focus an input - useRef  (1) 2024.03.07
[REACT] Simple calculator - useReducer  (1) 2024.03.07
[REACT] Pixel art - React Context  (0) 2024.03.07