ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 자바스크립트 화살표 함수
    카테고리 없음 2020. 6. 18. 12:39

    화살표 기능은 ES6에서 도입되었습니다.

    화살표 함수를 사용하면 더 짧은 함수 구문을 작성할 수 있습니다.

    // before
    hello = function() {
      return "Hello World!";
    }
    
    // after
    hello = () => {
      return "Hello World!";
    }

    함수가 하나의 문이 있고 문은 값을 반환하는 경우에는 괄호 제거 할 수 있습니다.

    // can return
    hello = () => "Hello World!";

    인자가 있는 화살표 함수

    hello = (val) => "Hello " + val;

    인자가 하나인 경우 괄호를 제거할 수 있다.

    hello = val => "Hello " + val;

    'this' 화살표 기능은 일반 기능에 비해 처리 방법이 다릅니다.

    요컨대, 화살표 함수에는 this 바인딩이 없습니다.

    일반 함수에서 this키워드는 함수를 호출 한 객체를 나타 냈으며 이는 window, document, button 또는 기타 일 수 있습니다.

    화살표 기능을 사용하면 this키워드는 항상 화살표 기능 을 정의한 객체를 나타냅니다.

    차이점을 이해하기 위해 두 가지 예를 살펴 보겠습니다.

    두 예제 모두 페이지를로드 할 때와 사용자가 버튼을 클릭 할 때 다시 한 번 메소드를 두 번 호출합니다.

    첫 번째 예는 일반 기능을 사용하고 두 번째 예는 화살표 기능을 사용합니다.

    결과는 첫 번째 예제가 두 개의 다른 오브젝트 (window 및 tag)를 리턴하고 두 번째 예제는 창 오브젝트가 함수의 "소유자"이기 때문에 창 오브젝트를 두 번 리턴 함을 보여줍니다.

    // With a regular function this represents the object that calls the function:
    
    hello = function() {
      document.getElementById("demo").innerHTML += this;
    }
    
    //The window object calls the function:
    window.addEventListener("load", hello);
    
    //A button object calls the function:
    document.getElementById("btn").addEventListener("click", hello);
    //Arrow Function:
    //With an arrow function this represents the owner of the function:
    
    hello = () => {
      document.getElementById("demo").innerHTML += this;
    }
    
    //The window object calls the function:
    window.addEventListener("load", hello);
    
    //A button object calls the function:
    document.getElementById("btn").addEventListener("click", hello);

    출처: https://www.w3schools.com/js/js_arrow_function.asp

    댓글

Designed by Tistory.