Arrow function

What is arrow function and why you should use it

javascriptes6

2018-04-25


๊ฐœ์ธ์ ์ธ ๊ณต๋ถ€ ๋…ธํŠธ๋กœ, ์˜ค๋ฅ˜๊ฐ€ ์žˆ์„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

1. Syntax

es6์—์„œ ์†Œ๊ฐœ๋œ arrow function๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ์•„๋ž˜์™€ ๊ฐ™์ด ๊ฐ„๊ฒฐํ•˜๊ฒŒ ํ•จ์ˆ˜๋ฅผ ์ •์˜ํ•  ์ˆ˜ ์žˆ๋‹ค.

/* using function keyword */
function method() {
  // do something...
}

/* ES6 arrow function */
const method = () => {
  // do something...
}

์ธ์ž๊ฐ€ ํ•˜๋‚˜๋ผ๋ฉด ()์—†์ด ์•„๋ž˜์ฒ˜๋Ÿผ ์จ๋„ ๋œ๋‹ค.

handleClick = e => { 
  e.preventDefault() 
}

2. this

  • ์ผ๋ฐ˜์ ์œผ๋กœ this๋Š” caller์— ๋”ฐ๋ผ ์ •ํ•ด์ง„๋‹ค. ์ฆ‰, this๋Š” ์‹คํ–‰ ์‹œ์˜ ์ปจํ…์ŠคํŠธ์— ๋”ฐ๋ผ ๋ฐ”์ธ๋”ฉ๋œ๋‹ค.
  • ๊ทธ๋Ÿฌ๋‚˜ arrow function์—์„œ๋Š” this๊ฐ€ caller์— bound๋˜์ง€ ์•Š๋Š”๋‹ค. ๐Ÿ‘‰ ๋Œ€์‹  ๊ทธ function์„ ๊ฐ์‹ธ๋Š” lexical context์˜ this๋ฅผ ๊ฐ€๋ฆฌํ‚จ๋‹ค.(์ถœ์ฒ˜)

์ด๋ฒคํŠธ ๋ฆฌ์Šค๋„ˆ ์•ˆ์—์„œ arrow function์„ ์“ฐ๋ฉด this๊ฐ€ ๊ฐ€๋ฆฌํ‚ค๋Š” ๊ฒƒ์ด ๊ทธ ๋ฐ”๊นฅ ์Šค์ฝ”ํ”„๊ฐ€ ๋œ๋‹ค.

  • arrow function ์•ˆ์—์„œ this๋ฅผ ์‚ฌ์šฉํ–ˆ์„ ๋•Œ: this๋Š” arrow function์ด ์•„๋‹ˆ๋ผ enclosing lexical context์ธ window๋ฅผ ๊ฐ€๋ฆฌํ‚จ๋‹ค.

    /* arrow function */
    const button = document.querySelector('button')
    button.addEventListener('click', () => {
    console.log(this) // window
    this.classList.toggle('on') // ์—ฌ๊ธฐ์„œ this๋Š” window ๊ฐ์ฒด๋ฅผ ๊ฐ€๋ฆฌํ‚ค๊ฒŒ ๋˜๊ณ , button์€ ์›ํ•˜๋Š” ๋Œ€๋กœ ์ž‘๋™ํ•˜์ง€ ์•Š๋Š”๋‹ค.
    })
  • function ํ‚ค์›Œ๋“œ๋ฅผ ์“ฐ๋ฉด ์›ํ•˜๋Š” button์— this ๋ฐ”์ธ๋”ฉ์ด ๋œ๋‹ค.

    /* refactor with function keyword */
    const button = document.querySelector('button')
    button.addEventListener('click', function() {
    this.classList.toggle('on') // ์—ฌ๊ธฐ์„œ this๋Š” button์„ ๊ฐ€๋ฆฌํ‚จ๋‹ค.
    })

    ์ถœ์ฒ˜ - https://wesbos.com/arrow-function-no-no/


3. .bind(this) in React

  • element ์ด๋ฒคํŠธ์˜ ์ฝœ๋ฐฑ์œผ๋กœ ๋ฉ”์†Œ๋“œ๋ฅผ ์‹คํ–‰ํ•˜๋ฉด, ์‹คํ–‰ ์‹œ์˜ context์— ๋”ฐ๋ผ this ๋Š” ํด๋ž˜์Šค๊ฐ€ ์•„๋‹Œ window๋ฅผ ๊ฐ€๋ฆฌํ‚ค๊ฒŒ ๋œ๋‹ค.
class MyComponent extends React.Component {
  handleClick() {
    console.log(this) // window
    this.setState({ open: false })  // ์ œ๋Œ€๋กœ ์‹คํ–‰๋˜์ง€ ์•Š๋Š”๋‹ค. 
  }
  render() {
    return (
      <button onClick={this.handleClick}/>  // handleClick()์€ MyComponent์˜ ๋ฉ”์†Œ๋“œ์ด์ง€๋งŒ, this๋Š” MyComponent๊ฐ€ ์•„๋‹ˆ๋ผ undefined๊ฐ€ ๋œ๋‹ค.
    )
  }
}
class MyComponent extends React.Component {
  state = { open: false }
  handleClick = () => { // arrow function์—์„œ๋Š” this์˜ ๋งฅ๋ฝ์ด ์ด๋ฅผ ๊ฐ์‹ธ๋Š” ์ปจํ…์ŠคํŠธ์ด๋‹ค.
    console.log(this) // MyComponent
    this.setState({ open: false })
  }
  render() {
    return (
      <button onClick={this.handleClick}/>  // ์—ฌ๊ธฐ์„œ handleClick ์‹คํ–‰๋  ๋•, handleClick์„ ๊ฐ์‹ธ๊ณ  ์žˆ๋Š” MyComponent๊ฐ€ this๊ฐ€ ๋œ๋‹ค. ๋”ฐ๋ผ์„œ ๋ฉ”์†Œ๋“œ๊ฐ€ ์ œ๋Œ€๋กœ ์‹คํ–‰์ด ๋œ๋‹ค.
    )
  }
}