본문 바로가기
Programing/Javascript

[JavaScript] When You Should Not Use Arrow Functions

by 멍멍돌이야 2022. 6. 28.
반응형

When You Should Not Use Arrow Functions

(화살표 기능을 사용하면 안 되는 경우)

화살표 함수에는 자체 this 값과 arguments 객체가 없습니다. 따라서 이벤트 핸들러, 객체 리터럴의 메서드, 프로토타입 메서드 또는 인수 객체를 사용하는 함수가 있는 경우에는 사용하지 않아야 합니다.

 

1) Event handlers

다음 입력 텍스트 필드가 있다고 가정합니다.

<input type="text" name="username" id="username" placeholder="Enter a username">

그리고 사용자가 사용자 이름을 입력할 때 <div> 요소에 인사말 메시지를 표시하려고 합니다.

 

<div id="greeting"></div>

사용자가 사용자 이름을 입력하면 입력의 현재 값을 캡처하고 이를 <div>요소에 출력합니다.

const greeting = document.querySelector('#greeting');
const username = document.querySelector('#username');
username.addEventListener('keyup', () => {
  greeting.textContent = 'Hello ' + this.value;
});

그러나 코드를 실행하면 입력 내용에 관계없이 다음 메시지가 표시됩니다.

Hello undefined

이벤트 핸들러에서 반환되는 값에는 this를 참조하지않습니다. 화상표 함수에는 this.value자체가 없어서 undefined값이 출력됩니다.

화살표에서 this는 전역 객체를 참조합니다.

 

이 문제를 해결하려면 대신 일반 함수를 사용해야 합니다. 그래야 이벤트 핸들러 this값이 바인딩됩니다

username.addEventListener('keyup', function () {
    input.textContent = 'Hello ' + this.value;
});

 

2) Object methods

다음의 counter object를 참조하십시오.

const counter = {
  count: 0,
  next: () => ++this.count,
  current: () => this.count
};

counter객체에는 두 가지 함수가 있습니다.

current()메서드는 현재 카운터 값을 반환하고, next()메서드는 다음 카운터 값을 반환합니다.

다음은 1이어야 하는 다음 카운터 값을 보여줍니다.

console.log(counter.next());

그러나, 반환값은  NaN 입니다.

 

그 이유는 객체 내부에서 화살표 함수를 사용할 때 상속을 받기 때문입니다. this는  전역 범위의 값입니다.

이 문제를 해결하려면 다음과 같이 객체 리터럴의 메서드로 일반 함수를 사용합니다.

const counter = {
    count: 0,
    next() {
        return ++this.count;
    },
    current() {
        return this.count;
    }
};

이제 next()메서드 호출하여 예상대로 1을 반환합니다.

console.log(counter.next()); // 1

 

3) Prototype methods

Counter사용하는 개체 prototype 패턴을 참조하십시오.

function Counter() {
    this.count = 0;
}

Counter.prototype.next = () => {
    return this.count;
};

Counter.prototype.current = () => {
    return ++this.next;
}

next(), current() 함수안의 this는 전역 개체를 참조합니다.

Counter 개체 내부의 this값을 참조할려면  일반 함수를 사용해야 합니다.

function Counter() {
    this.count = 0;
}

Counter.prototype.next = function () {
    return this.count;
};

Counter.prototype.current = function () {
    return ++this.next;
}

 

4) arguments 객체를 사용하는 함수

화살표 함수에는 arguments 객체를 사용할수 없습니다. 예를 들어, 다음 concat()기능이 작동하지 않습니다:

const concat = (separator) => {
    let args = Array.prototype.slice.call(arguments, 1);
    return args.join(separator);
}

대신 다음과 같은 일반 함수를 사용합니다.

function concat(separator) {
    let args = Array.prototype.slice.call(arguments, 1);
    return args.join(separator);
}

 

요약

  • 화살표 함수에는 고유한 this 값이 없습니다. 대신 포함하는 어휘 범위의 this 값을 사용합니다. 화살표 함수에는 또한 arguments 객체가 없습니다.
  • 이벤트 핸들러, 객체 메서드, 프로토타입 메서드 및 arguments 객체를 사용하는 함수에 화살표 함수를 사용하지 마십시오.

 

 

 

 

 

 

 

 

참고: https://www.javascripttutorial.net/es6/when-you-should-not-use-arrow-functions/

 

728x90
반응형

댓글