[javascript] 화살표 함수와 function 함수의 차이

insung·2025년 4월 18일

학습자료 : https://www.youtube.com/watch?v=eDcaBeaOrqI

JavaScript에서 함수 정의 방식인 function 키워드 함수와 화살표 함수는 문법, 동작 방식에서 주요 차이점 가짐.

1. 반환 방식 (Implicit Return)

  • 화살표 함수: 코드 블록 {} 없이 한 줄 작성 시, return 생략 가능. 표현식 결과 자동 반환.
    // 화살표 함수 (암시적 반환)
    const add = (a, b) => a + b;
    console.log(add(1, 2)); // 출력: 3
    
    // function 함수
    function subtract(a, b) {
      return a - b;
    }
    console.log(subtract(5, 3)); // 출력: 2
  • function 함수: 항상 명시적으로 return 사용해야

2. arguments 객체

  • function 함수
    • 함수 내 arguments 객체로 모든 전달 인자 접근 가능. 명시적 매개변수 외 인자 포함.

      function sumAll() {
        let total = 0;
        for (let i = 0; i < arguments.length; i++) {
          total += arguments[i];
        }
        return total;
      }
      console.log(sumAll(1, 2, 3)); // 출력: 6
      console.log(sumAll(10, 20));   // 출력: 30
  • 화살표 함수: arguments 객체 없음. 나머지 매개변수 (...)로 인자 배열로 받음.
    const multiplyAll = (...args) => {
      let product = 1;
      for (const num of args) {
        product *= num;
      }
      return product;
    };
    console.log(multiplyAll(2, 3, 4)); // 출력: 24
    console.log(multiplyAll(5, 10));   // 출력: 50

3. this 바인딩

function 키워드 함수 this: 호출 방식 따라 동적 결정.

화살표 함수 this: 정적으로 상위 스코프 this 참조.

3.1. function 키워드 함수 this 바인딩 방식

  • 일반 함수 호출:
    • this -> 전역 객체 (window in 브라우저, global in Node.js).

    • strict mode: undefined.

      function myFunction() {
        console.log(this);
      }
      myFunction(); // 브라우저: Window 객체, Node.js: global 객체
  • 메서드 호출: this -> 메서드 호출 객체.
    const myObject = {
      name: '철수',
      greet: function() {
        console.log(`안녕하세요, 제 이름은 ${this.name}입니다.`);
      }
    };
    myObject.greet(); // 출력: 안녕하세요, 제 이름은 철수입니다.
  • 생성자 함수 호출: new 키워드 호출 시 this -> 새로 생성된 인스턴스 객체.
    function Person(name) {
      this.name = name;
    }
    const person1 = new Person('영희');
    console.log(person1.name); // 출력: 영희
  • 이벤트 핸들러: this -> 이벤트 발생 DOM 요소.JavaScript
    // <button id="myButton">클릭하세요</button>
    const button = document.getElementById('myButton');
    button.addEventListener('click', function() {
      console.log(this); // 출력: <button id="myButton">클릭하세요</button>
    });
  • call, apply, bind: this 명시적 바인딩 가능.
    function sayHello(greeting) {
      console.log(`${greeting}, ${this.name}!`);
    }
    const person = { name: '수지' };
    sayHello.call(person, '안녕');   // 출력: 안녕, 수지!
    sayHello.apply(person, ['반가워']); // 출력: 반가워, 수지!
    const greetPerson = sayHello.bind(person, '좋은 아침');
    greetPerson();                   // 출력: 좋은 아침, 수지!

3.2. 화살표 함수 this 바인딩

화살표 함수: 자체 this 컨텍스트 생성 안 함. 렉시컬 스코프 따라 정의 시점 상위 스코프 this 참조.

const myObjectArrow = {
  name: '지수',
  greet: () => {
    console.log(`안녕하세요, 제 이름은 ${this.name}입니다.`); // this -> 상위 스코프 this
  }
};
myObjectArrow.greet(); // 브라우저 환경 따라 Window 또는 undefined 출력

function PersonArrow(name) {
  this.name = name;
  this.delayedGreet = () => {
    setTimeout(() => {
      console.log(`안녕하세요, ${this.name}님 (화살표 함수)`); // this -> PersonArrow this
    }, 100);
  };
  this.delayedGreetFunction = function() {
    setTimeout(function() {
      console.log(`안녕하세요, ${this.name}님 (function 함수)`); // this -> 전역 객체 (strict mode: undefined)
    }, 100);
  };
}

const personArrow = new PersonArrow('민준');
personArrow.delayedGreet();       // 출력: 안녕하세요, 민준님 (화살표 함수) (약 100ms 후)
personArrow.delayedGreetFunction(); // 출력: 안녕하세요, undefined님 (function 함수) (약 100ms 후)

3.3. 화살표 함수 this -> 상위 스코프 참조 이유

function 키워드 함수 this 바인딩: 유연하나 예측 어려움, 오류 유발. 콜백 함수 등에서 this가 의도한 객체 미참조 문제 빈번.

화살표 함수: this 바인딩 예측 불가능성 해결 위해 도입. 정의 시점 상위 스코프 this 항상 참조하도록 설계. this 값 일관성 보장, 코드 흐름 따라 this 참조 값 쉽게 예측 가능. 콜백 함수 내 외부 스코프 this 유지를 위한 bind, call, apply 명시적 사용 번거로움 줄여줌.

profile
안녕하세요 프론트엔드 관련 포스팅을 주로 하고 있습니다

0개의 댓글