Javascript - 함수 만드는 법 , arrow function & this binding

정세형·2023년 2월 25일
0

javascript

목록 보기
30/30

제일 최신 문법 인 Arrow function을 위주로 설명한다.

화살표 함수 (Arrow Function)

ES6에서 추가된 새로운 함수 표현식입니다. 간단한 함수를 만들 때 유용합니다.


let functionName = (parameter1, parameter2, ...) => {
  return parameter1 + parameter2;
};
  • 파라미터가 하나 라면 소괄호 생략이 가능합니다.
let functionName = parameter1 => {
  return parameter1 * 2;
};
  • 중괄호 안에 return이 한줄이면 중괄호와 return도 생략 가능합니다.
let functionName = parameter1 =>  
return parameter1 * 2;

함수 선언문 (Function Declaration)

함수 이름과 매개변수를 지정하여 함수를 만드는 가장 일반적인 방법입니다. 함수 선언문은 함수를 선언하기 이전에 호출해도 실행됩니다.

function functionName(parameter1, parameter2, ...) {
  return  parameter1 + parameter2;
}

함수 선언문에는 세미클론이 없습니다!

함수 표현식 (Function Expression)

변수에 함수를 할당하여 함수를 만드는 방법입니다. 함수 표현식은 변수가 선언된 이후에만 호출할 수 있습니다.


var functionName = function(parameter1, parameter2, ...) {

  return  parameter1 + parameter2;
};

함수표현식에는 세미클론이 있습니다.

Arrow Function과 Function Declaration의 가장 큰 차이 (this 바인딩)

Arrow FunctionFunction Declaration의 가장 큰 차이 중 하나는 this 바인딩입니다.

  • Function Declaration에서 함수가 호출될 때마다 this 값이 동적으로 결정됩니다. this는 호출되는 컨텍스트에 따라 결정되며, 함수를 메서드로 사용하는 경우, 메서드를 호출한 객체가 this가 됩니다.
const obj = {
  name: 'object',
  getName: function() {
    console.log(this.name); // 'object'
  }
}

obj.getName();

위 코드에서 getName 메서드는 Function Declaration으로 정의되어 있습니다. getName이 호출되는 시점에서 this 값은 obj 객체를 참조하게 됩니다. 따라서 object가 출력됩니다.

하지만, getName 메서드를 다른 객체에서 호출하면 this 값은 호출한 객체를 참조하게 됩니다.

const anotherObj = {
  name: 'another object'
}

obj.getName.call(anotherObj); // 'another object'
  • 반면에, Arrow Function은 함수를 선언할 때 this를 바인딩하며, 실행 중에 this 값이 변경되지 않습니다. Arrow Function에서 this 값은 선언 시점에 정적으로 결정되며, 상위 스코프의 this 값을 그대로 참조합니다.

아래 예시를 통해 더 자세히 살펴보겠습니다.

const obj = {
  name: 'object',
  getName: function() {
    console.log(this.name); // 'object'
    const arrowFunction = () => {
      console.log(this.name); // 'object'
    }
    arrowFunction();
    function normalFunction() {
      console.log(this.name); // undefined
    }
    normalFunction();
  }
}
obj.getName();

위 예시에서 getName 메서드는 Function Declaration으로 정의되었으며, arrowFunctionArrow Function으로 정의되었습니다. arrowFunction 내부의 this 값은 getNamethis 값을 그대로 참조하므로 object가 출력됩니다.

반면 normalFunctionFunction Declaration으로 정의되었으며, 호출 시점의 this 값에 따라 동적으로 바인딩됩니다. 따라서 normalFunction 내부의 this 값은 undefined가 됩니다.

하지만, arrowFunction을 전역 스코프에서 선언하면 this 값은 전역 객체를 참조하게 됩니다. 다음과 같이 코드를 작성하면 this 값은 전역 객체를 참조하게 됩니다.

const arrowFunction = () => {
  console.log(this); // Window {...}
}
arrowFunction();

Arrow Function은 함수를 선언할 때 this 값을 결정하기 때문에, bind, call, apply와 같은 메서드로 this 값을 변경할 수 없습니다.

profile
👨‍💻github.com/pos1504 💌pos1504@gmail.com 🙋‍♂️https://www.linkedin.com/in/%EC%84%B8%ED%98%95-%EC%A0%95-68067b287/

0개의 댓글