Skip to content

26. ES6 함수의 추가 기능 #135

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open

26. ES6 함수의 추가 기능 #135

wants to merge 3 commits into from

Conversation

L2HYUNN
Copy link
Member

@L2HYUNN L2HYUNN commented Mar 28, 2023

26. ES6 함수의 추가 기능

✏️ 기억에 남는 내용

  • ES6에서는 함수를 사용 목적에 따라 다음과 같은 세 가지 종류로 명확히 구분했다.

    • 일반 함수 (Normal)
    • 메서드 (Method)
    • 화살표 함수 (Arrow)
  • ES6 이전 사양에는 메서드에 대한 명확한 정의가 없었다. ES6 사양에서 메서드는 메서드 축약 표현으로 정의된 함수만을 의미한다.

    • ES6 사양에서 메서드는 인스턴스를 생성할 수 없는 non-constructor다.
    • ES6 메서드는 자신을 바인딩한 객체를 가리키는 내부 슬롯 [[HomeObject]]를 갖는다.
  • 화살표 함수와 일반 함수의 차이

    1. 화살표 함수는 인스턴스를 생성할 수 없는 non-constructor다.
    2. 중복된 매개변수 이름을 선언할 수 없다.
    3. 화살표 함수는 함수 자체의 this, arguments, super, new.target 바인딩을 갖지 않는다.
  • 화살표 함수의 this는 일반 함수의 this와 다르게 동작한다. 이를 통해 "콜백 함수 내부의 this 문제", 즉 콜백 함수 내부의 this가 외부 함수의 this와 다르기 때문에 발생하는 문제를 해결할 수 있다.

    • ES6 이전에는 콜백 함수의 this와 내부 함수의 this를 동일하게 사용하기 위해 외부 this를 내부에 전달하는 방식을 사용하였다.
    • 화살표 함수는 함수 자체의 this 바인딩을 갖지 않는다. 따라서 화살표 함수 내부에서 this를 참조하면 상위 스코프의 this를 그대로 참조하여 외부 this와 내부 this를 동일하게 사용할 수 있다.
    • 화살표 함수의 this가 함수가 정의된 위치에 의해 결정되는 것을 lexical this라 한다.
  • 화살표 함수 내부에서 super를 참조하면 this와 마찬가지로 상위 스코프의 super를 참조한다.

  • 화살표 함수 내부에서 arguments를 참조하면 this와 마찬가지로 상위 스코프의 arguments를 참조한다.

  • Rest 파라미터는 함수에 전달된 인수들의 목록을 배열로 전달받는다.

  • arguments 객체는 배열이 아닌 유사 배열 객체이므로 배열 메서드를 사용하려면 Function.prototype.call 이나 Function.prototype.apply 메서드를 사용해 arguments 객체를 배열로 변환해야 한다.


📝 간단한 퀴즈

  1. 자바스크립트의 함수는 다양한 형태로 호출할 수 있다. 자바스크립트의 함수 호출 방법을 모두 작성하고 어느 시점에 어떤 호출 방법을 사용해야 할지 간단하게 이야기해보자.

  2. 화살표 함수와 일반 함수의 차이를 간단하게 작성해보자.

  3. "콜백 함수 내부의 this문제"가 무엇인지 간단하게 작성하고 그 해결 방법을 화살표 함수와 연관지어 작성해보자. (화살표 함수가 없던 ES6 이전에는 이 문제를 어떻게 해결했을까?)


🧑🏻‍💻 연관 코드

class Prefixer {
  constructor(prefix) {
    this.prefix = prefix;
  }

  add1(arr) {
    return arr.map(function (item) {
      return this.prefix + item;
    });
  }

  add2(arr) {
    const that = this;
    return arr.map(function (item) {
      return that.prefix + item;
    });
  }

  add3(arr) {
    return arr.map((item) => this.prefix + item);
  }
}

const prefixer = new Prefixer("-webkit");

@L2HYUNN L2HYUNN self-assigned this Mar 28, 2023
@L2HYUNN L2HYUNN linked an issue Mar 28, 2023 that may be closed by this pull request
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

26. ES6 함수의 추가 기능
1 participant