ES6 화살표 기능: 알아야 할 모든 것

ES6에는 더 짧고 깔끔한 코드를 작성하는 방법을 제공하는 화살표 함수가 도입되었습니다.

// Old way
function squareOld(number) {
    return number ** 2;
}

// ES6 way
const squareNew = number => number ** 2;

// Callbacks become cleaner
let array = [1, 2, 3, 4, 5, 6];

// Old
array.filter(function(value) {
    return value % 2 === 0;
});
// [2, 4, 6]

// ES6
array.filter(value => value % 2 === 0);
// [2, 4, 6]


다음 사항에 유의하십시오.
  • 화살표 함수 구문은 변수에 저장해야 하는 함수를 반환합니다.
  • return 키워드를 쓰지 않습니다. 함수 정의가 한 줄이면 해당 줄의 출력이 반환됩니다
  • .
  • 인수 주위에 대괄호가 없습니다 number . (인자가 둘 이상인 경우는 해당되지 않음)

  • 화살표 구문




    // No arguments
    const sayHi = () => console.log("Hi");
    
    // One argument, One line
    const addFive = number => number + 5;
    
    // Multiple arguments, One line
    const addNumbers = (a, b) => a + b;
    
    // One argument, Multiple lines
    const doStuffAndAddFive = number => {
        let flavour = "vanilla";
        makeIceCream(flavour);
        eatIceCream();
        return number; /* Note that here we have to use the return keyword */
    };
    
    // Multiple arguments, Multiple lines
    const doStuffAndAddNumbers = (a, b) => {
        let flavour = "vanilla";
        makeIceCream(flavour);
        eatIceCream();
        return a + b;
    };
    


    바닐라 함수의 바인딩



    바인딩은 화살표 기능을 바닐라 기능과 구별하는 것입니다. 모든 함수는 this 변수에 액세스할 수 있습니다.

    다음을 고려하세요:

    function getThis() {
        return this;
    }
    getThis();
    // returns the global object
    


    위의 함수는 호출될 때 전역 객체를 반환합니다.

    이제 이것을 고려하십시오.

    let obj = {
        fruit: "Apple",
        calories: 100,
        getThis: function() {
            return this;
        }
    };
    
    obj.getThis();
    // returns the obj object
    


    이제 ES6 클래스 예제를 살펴보겠습니다.

    class Fruit {
        constructor(name, calories) {
            this.name = name;
            this.calories = calories;
        }
        getThis() {
            return this;
        }
    }
    
    let apple = new Fruit("Apple", 97);
    apple.getThis();
    // returns apple
    


    특이한 경우:

    let person = {
        name: "Sally",
        getName: function() {
            return this.name;
        }
    };
    
    let name = "Sergie";
    
    person.getName();
    // "Sally"
    
    let foo = person.getName;
    
    foo();
    // "Sergie"
    

    person.getName() 를 호출했을 때 this는 person 객체를 참조했습니다. 그런 다음 foo 와 같은 정의로 person.getName를 초기화할 때 this 전역 개체를 참조했습니다.
    this 키워드가 가리키는 위치를 파악하는 방법은 무엇입니까?

    대부분의 경우 작동하는 좋은 "해킹"은 함수 호출 앞에 점 연산자가 있는지 확인하는 것입니다. 그렇다면 함수 정의의 this는 점 연산자 앞의 객체를 참조합니다. 위의 경우 person.getName() 에서 thisperson 를 참조하게 되었습니다. 점 연산자가 없으면 this 일반적으로 전역 개체를 참조합니다.

    이것은 규칙이 아니라 해킹일 뿐입니다.

    화살표 함수 바인딩


    this의 바인딩이 정의 자체가 아니라 어휘적으로 정의된 위치에 따라 변경되는 바닐라 함수와 달리 화살표 함수의 바인딩은 어디에서나 동일하게 유지됩니다.

    화살표 기능이 있는 이전 코드를 살펴보겠습니다.

    let person = {
      name: "Sally",
      getName: () => this.name;
    }
    
    let name = "Sergie";
    
    person.getName();
    // "Sergie"
    
    let foo = person.getName;
    
    foo();
    // "Sergie"
    


    따라서 두 경우 모두 화살표 함수는 this 로 전역 객체를 참조했습니다. 화살표 함수의 경우 this 바인딩이 변경되지 않습니다. 화살표 함수의 this 개체가 가리키는 위치를 확인하는 또 다른 방법은 화살표 함수를 선언하기 직전에 this 값이 무엇인지 관찰하는 것입니다.

    let object = {
        whatsThis: this,
        getThisNew: () => this,
        getThisOld: function() {
            return this;
        }
    };
    
    object.whatsThis();
    // global
    
    object.getThisNew();
    // global
    
    object.getThisOld();
    // object
    


    지금까지 우리가 알고 있는 것을 ES6 클래스의 경우에 테스트해보자. this가 참조하는 개체와 달리 개체 자체를 참조하지 않는 클래스에서는 클래스의 인스턴스를 참조합니다.

    class Fruit {
        constructor(name) {
            this.name = name;
        }
        getNameOld() {
            return this.name;
        }
        getNameNew = () => this.name;
    }
    
    // global variable
    let name = "Sally";
    
    let apple = new Fruit("Apple");
    
    apple.getNameNew();
    // "Apple"
    
    apple.getNameOld();
    // "Apple"
    
    // Now let's make two new functions:
    let foo = apple.getNameOld;
    let bar = apple.getNameNew;
    
    foo();
    // "Sally"
    
    bar();
    // "Apple"
    

    foo"Sally" 객체에 바인드되어 bar 반환되는 동안 apple 가 전역 객체에 바인딩될 때 "Apple" 가 어떻게 반환되었는지 주목하십시오.

    따라서 요약하면 바닐라 함수는 점 연산자 "hack"을 따르는 반면 화살표 함수는 함수가 정의되기 직전에 있던 this 값에 바인딩된 상태로 유지됩니다. 이 바인딩은 바닐라 맛과 달리 함수가 다시 선언되더라도 유지됩니다.

    And that is all that you need to know about the ES6 Arrow Functions. If you found a mistake or have some doubt, let me know in the comments. Thank You for reading and have a wonderful day 😄

    좋은 웹페이지 즐겨찾기