자바스크립트 화살표 함수

Javascript Arrow는 이전 일반 함수에 대한 대체 구문입니다.

자바 스크립트 화살표 기능을 사용하는 두 가지 주요 사용 사례가 있습니다. 첫 번째는 아래와 같이 코드를 더 짧고 간결하게 만든다는 것입니다.


인수 없음



// Regular Function
function sayHello() {
  return 'Hello'
}

// Arrow Function
const sayHello = () => 'Hello'




하나의 인수



// Regular Function
function addTen(number) {
  return number + 10
}

// Arrow Function
// Notice that we can remove the parenthesis around the parameter when argument is just one. It is optional.
const addTen = num => number + 10 




여러 함수 본문 문이 있는 둘 이상의 인수. 여러 함수 본문 문에 대해 중괄호와 return 키워드를 유지해야 합니다.



// Regular Function
function addTen(number1, number2) {
  const ten = 10                   // function body line #1
  return number1 + number2 + 10    // function body line #2
}

// Arrow Function
const addTen = (number1, number2) => {
  const ten = 10
  return number1 + number2 + 10
}


화살표 함수의 두 번째 사용 사례는 범위를 더 잘 처리하는 것입니다. 아주 간단한 예를 보자.

const person = {
    myName: John Doe,
    sayName () {
        setTimeout(function() {
             console.log(`Hi, ${this.myName}`)
        }, 1000)
    }
}


우리가 호출할 때

person.sayName() 


우리는 볼 것으로 기대합니다

Hi, John Doe


불행히도, 아래에 얻을 것이다.
함수가 창 개체를 가리키고 있고 창 개체에 sayName이라는 메서드가 없기 때문입니다.

Hi, undefined


컨텍스트 문제를 해결하기 위해 엔지니어는 다음 해결 방법을 사용합니다.

수정 #1:




// Save the context and use that context
const person = {
    myName: John Doe,
    sayName () {
        const _this = this
        setTimeout(function() {
             console.log(`Hi, ${_this.myName}`)
        }, 1000)
    } 
}


수정 #2:




// Use bind to ensure that context is set and kept
const person = {
    myName: John Doe,
    sayName () {
        setTimeout(function() {
             console.log(`Hi, ${this.myName}`)
        }.bind(this), 1000)
    } 
}


수정 #3 - 최신 솔루션



화살표 함수는 변수처럼 작동하며 화살표 함수가 생성된 this(컨텍스트)의 값을 설정합니다.

// Using Arrow Function. 
const person = {
    myName: John Doe,
    sayName () {
        setTimeout(() => console.log(`Hi, ${this.myName}`), 1000)
    } 
}


대신 5분짜리 동영상을 보고 싶다면 아래 링크를 참조하세요.



저를 지원하고 싶다면 - Buy Me A Coffee

좋은 웹페이지 즐겨찾기