현재, 자바스크립트에는 함수를 선하는 방법이 2가지 있습니다.

  1. Arrow function () => {}
  2. function

오늘은 이 두 가지의 다른 부분에 대해서 알아보고자 합니다.

 

 

1. this

일반 function에서는 this가 함수가 불려지는 방법에 따라 바뀝니다.

  • simple invocation (단순 호출): this는 전역 오브젝트와 같거나, 1strict1 모드를 사용한다면 정의되지 않을 수 있습니다.
  • method invocation(메서드 호출): method this를 소유한 오브젝트와 같습니다.
  • indirect invocation(간접 호출): this는 첫 번째 인자와 같습니다.
  • constructor invocation(생성자 호출): `this1는 새롭게 생성된 instance와 같습니다.
// Simple Invocation
function simpleInvocation() {
  console.log(this);
}
simpleInvocatoin(); // logs global object
--------------------------------------------------------------------
// Method Invocation
const methodInvocation= {
  method() {
    console.log(this);
  }
};
methodInvocation.method(); // logs methodInvocation object
--------------------------------------------------------------------
// Indirect Invocation
const context = { value1: 'A', value2: 'B' };
function indirectInvocation() {
  console.log(this);
}
indirectInvocation.call(context);  // logs { value1: 'A' }
indirectInvocation.apply(context); // logs { value1: 'A' }
--------------------------------------------------------------------
// Constructor Invocation
function constructorInvocation() {
  console.log(this);
}

new constructorInvocation(); // logs an instance of constructorInvocation

 

 

Arrow function에서는, this의 행동이 완전히 바뀝니다.

Arrow functionthis 자체가 없으며, 함수 내에서 this를 재정의하지 않습니다.

 

Arrow function의 이런 점은, 메소드 안에 callback을 사용할 때 매우 유용합니다.

const selft = this 또는 Arrow function과 함께 callback.bind(this)와 같이 사용하지 않아도 됩니다.

그리고, callback안에 this로 사용하여 발생하는 실수를 방지할 수 있습니다.

 

 

 

2. Argument object

일반 javascript 함수에서 arguments 키워드는 함수가 호출될 때 전달된 인수를 access하는 데 사용합니다.

예를 들어, 3개의 인자로 함수를 부른다면 다음과 같이할 수 있습니다.

 

하지만, Arrow function은 그 자체의 인자를 가질 수 없고, 외부 함수를 통해 인자를 사용할 수 있습니다.

 

하지만, Arrow function에서 인수를 직접 access하려면, ...args 기능을 사용할 수 있습니다.

 

 

 

3. Constructors(생성자) / new keyword

new 키워드로 함수를 호출하기만 하면, 일반 function으로 쉽게 객체를 생성할 수 있습니다.

function Article(topic) {
  this.topic= topic;
}

const article= new Article('JavaScript');

 

 

 

 

4. Implicit return (암시적 반환)

 

일반 function에서는, return을 사용하여 함수로부터 반환값을 받을 수 있습니다.

return 을 주지 않는다면, function은 암시적으로 undefined를 반환할 것입니다.

function exampleFunction() {
 return 10;
}
exampleFunction(); // output -> 10
--------------------------------------------------------------------
function exampleFunction() {
 var number  = 10;
}
exampleFunction(); // output -> undefined
--------------------------------------------------------------------
function exampleFunction() {
 var number  = 10;
  return;
}
exampleFunction(); // output -> undefined

Arrow function은 같은 방식으로 반환 값을 돌려주지만, 장점이 하나 있습니다.

만얀 Arrow function이 하나의 표현식을 가지고 있다면, curly braces {} 를 생랼할 수 있습니다ㅏ. 그리고 암시적으로 해당 표현식이 반환됩니다.

+ 추가

Promise, Dynamic context 가 있는 callback 함수, Object method를 다루는 상황에서는 에서는 Arrow function을 사용하는 것을 피해야합니다.

 

 

 

 

이 글은 다음의 블로그를 해석했습니다.

https://blog.bitsrc.io/arrow-functions-vs-regular-functions-in-javascript-458ccd863bc1

 

Arrow Functions vs. Regular Functions in JavaScript

Learn when and when not to use the arrow function

blog.bitsrc.io

 

+ Recent posts