프로그래밍 공부/Javascript

화살표 함수

Kevinkb 2021. 7. 1. 18:46

화살표 함수 (Arrow function)

화살표 함수는 익명 함수를 더 간결하게 표현할 수 있도록 ES2015에서 새롭게 등장한 함수 선언방식이다. 다음과 같이 표현식으로 함수를 정의하거나 콜백함수로 전달할 때 활용할 수 있다.

// 화살표 함수 정의
const getTwice = (number) => {
  return number * 2;
};

// 콜백 함수로 활용
myBtn.addEventListener('click', () => {
  console.log('button is clicked!');
});

구문

화살표 함수는 다양한 상황에 따라 축약형으로 작성될 수 있다. 화살표 함수는 arguments 객체가 없고, this가 가르키는 값이 일반 함수와 다르다. (항상 window 객체를 가르킨다)

// 1. 함수의 파라미터가 하나 뿐일 때
const getTwice = (number) => {
  return number * 2;
};

// 파라미터를 감싸는 소괄호 생략 가능 (일부 스타일 가이드는 파라미터 구분을 위해 항상 소괄호 사용을 권장)
const getTwice = number => {
  return number * 2;
};


// 2. 함수 동작 부분이 return문만 있을 때
const sum = (a, b) => {
  return a + b;
};

// return문과 중괄호 생략 가능
const sum = (a, b) => a + b;

// 3. 파라미터가 없을 땐 괄호를 비운다. 이 때 괄호는 생략할 수 없다.
let sayHi = () => alert("안녕하세요!");

sayHi();

// 4. 객체 리터럴 표현을 반환하기 위해서는 함수본문을 괄호 속에 넣음
let sayHi = () => ({first: 'Hi', second: 'Hello'})

// 5. 나머지 파라미터 및 디폴트 파라미터를 지원함
(param1, param2, ...others) => { statements }
(param1 = defaultValue1, param2, …, paramN = defaultValueN) => { statements }

// 6. 매개변수 목록 내 구조분해할당도 지원한다.
var f = ([a, b] = [1, 2], {x: c} = {x: a + b}) => a + b + c;
f();  // 6

function solution(array, commands) {
    return commands.map(([sPosition, ePosition, kPosition]) => {
        return array.slice(sPosition - 1, ePosition).sort((a, b) => a - b)[kPosition - 1];
    })
}

1) arguments 객체가 없다.

function one() {
  console.log(arguments);
}

one();  // Arguments ...

let two = () => {
  console.log(arguments);
}

two();  // Error

2) this 바인딩하는 객체는 window이다.(화살표 함수에서의 this)

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

const myObj = {
  content: 'myObj',
  printThis: printThis,
}

const otherObj = {
  content: 'otherObj',
  printThis: printThis,
}

printThis();           // window
myObj.printThis();     // window
otherObj.printThis();  // window

일반 함수에서의 this

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

const myObj = {
  content: 'myObj',
  printThis: printThis,
}

const otherObj = {
  content: 'otherObj',
  printThis: printThis,
}

printThis();           // window
myObj.printThis();     // {content: "myObj", printThis: ƒ}
otherObj.printThis();  // {content: "otherObj", printThis: ƒ}


function getFullName() {
  return `${this.firstName} ${this.lastName}`;
}

const user = {
  firstName: 'Tess',
  lastName: 'Jang',
  getName: getFullName,
}

const admin = {
  firstName: 'Alex',
  lastName: 'Kim',
  getName: getFullName,
}

console.log(user.getName());   // Tess Jang
console.log(admin.getName());  // Alex Kim

'프로그래밍 공부 > Javascript' 카테고리의 다른 글

문장과 표현식  (0) 2021.07.02
함수 다루기 - 종합정리  (0) 2021.07.01
즉시 실행 함수(IIFE)  (0) 2021.06.29
기명 함수 표현식  (0) 2021.06.29
함수 선언과 함수 표현식  (0) 2021.06.29