개인노트 nomad ES6의 정석 #2 Functions

2023. 2. 1. 15:13개인노트-인강

# 2.0 Arrow Functions

 

화살표 함수

화살표 함수 표현(arrow function expression)은 전통적인 함수표현(function)의 간편한 대안입니다.
하지만, 화살표 함수는 몇 가지 제한점이 있고 모든 상황에 사용할 수는 없습니다.

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Functions/Arrow_functions

 

# 2.1 'this' in Arrow Function

 

대부분의 경우에 arrow function을 사용할 수 있습니다.

하지만, this 키워드를 사용해야하는 경우, arrow function을 사용하지 말아야할 때가 있습니다.

 

아래는 arrow function을 사용하지 말아야하는 두가지 경우입니다.

 

## 예시1

const button = document.querySelector("button");

function handleClick() {
  console.log(this);
}

button.addEventListener("click", handleClick);
// 결과 : button 객체 출력

const handleClick2 = () => {
  console.log(this);
}

button.addEventListener("click", handleClick2);
// 결과 : window 객체 출력

arrow function은 this를 이벤트로 부터 가지고 있지 않습니다.

arrow function은 this를 window object로 가지고 있습니다.

this를 사용하고 싶다면 function을 사용해야합니다.

 

## 예시2

const nico = {
  name: "Nico",
  age: 24,
  addYear: () => {
    this.age++;
  }
};

console.log(nico);
nico.addYear();
nico.addYear();
console.log(nico);

// 결과 { name: "Nico", age : 24, addYear: f }

// 아래처럼 하면 잘 동작합니다.
const nico = {
  name: "Nico",
  age: 24,
  addYear() {
    this.age++;
  }
};

age의 값이 26이 나와야 하지만, age의 값이 변하지 않았습니다. arrow function 안에서 this를 사용했기 때문입니다.

 

## 참고

 

화살표 함수 주의사항

this나 super에 대한 바인딩이 없고, methods 로 사용될 수 없습니다.
new.target키워드가 없습니다.
일반적으로 스코프를 지정할 때 사용하는 call, apply, bind methods를 이용할 수 없습니다.
생성자(Constructor)로 사용할 수 없습니다.
yield를 화살표 함수 내부에서 사용할 수 없습니다.

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Functions/Arrow_functions

 

# 2.2 Arrow Functions in the Real World

 

arrow function을 사용한 array operation 예시

1. Array.prototype.find() 와 Array.prototype.includes()

const emails = {
  "nco@no.com",
  "naver@google.com",
  "lynn@gmail.com",
  "nico@nomad.com"
};

const foundMail = emails.find(item => item.includes("@gmail.com"));

console.log(foundMail);

2. Array.prototype.filter()

const emails = {
  "nco@no.com",
  "naver@google.com",
  "lynn@gmail.com",
  "nico@nomad.com",
  "nico@gmail.com"
};

const noGmail = emails.filter(potato => !potato.includes("@gmail"));

console.log(noGmail);

3. Array.prototype.forEach() , Array.prototype.map()

const emails = {
  "nco@no.com",
  "naver@google.com",
  "lynn@gmail.com",
  "nico@nomad.com",
  "nico@gmail.com"
};

emails.forEach(email => { console.log(email.split("@")[0]) });

console.log(noGmail);
// 출력
// nco
// naver
// lynn
// nico
// nico

const cleaned = emails.map(email => email.split("@")[0]);

console.log(cleaned);
// 출력
// ["nco", "naver", "lynn", "nico", "nico"]

 

# 2.3 Default Values

 

const sayHi = (aName = "anon") => "hello " + aName;

console.log(sayHi());
// 출력
// hello anon
const DEFAULT = "lalalal";

const sayHi = (aName = DEFAULT) => "hello " + aName;

console.log(sayHi());
// 출력
// hello anon