arrow function

kiko·2022년 1월 10일

모던자바스크립트

목록 보기
5/10

화살표 함수를 사용해서 안 되는 경우

  • 메소드
const person = {
 name: 'Sally',
 sayHi: () => console.log(this.name)
}

person.sayHi() // undefined

메소드를 호출한 객체를 가리키지 않고, 상위 컨텍스트인 window를 가리킨다.

  • prototype
    메소드를 prototype에 할당하는 경우도 같은 문제 발생
  • 생성자 함수 (new)
    화살표 함수는 prototype 프로퍼티가 없다.
const Foo = () => {} // x
console.log(Foo.hasOwnProperty('prototype')); // false
const foo = new Foo() // TypeError: Foo is not a constructor
  • addEventListener 함수의 콜백 함수
    화살표 함수로 정의하면, this가 상위 컨택스트인 전역 객체 window를 가리킨다.
var button = document.getElementById('myButton');

// Bad
button.addEventListener('click', () => {
  console.log(this === window); // => true
  this.innerHTML = 'Clicked button';
});

// Good
button.addEventListener('click', function() {
  console.log(this === button); // => true
  this.innerHTML = 'Clicked button';
});

Quiz

  • function이랑 arrow function에 차이점을 설명하세요.
    keyword: this 동적/정적, Lexical this
    함수 호출 방식에 의해 this에 바인딩할 어떤 객체가 동적/정적이 결정된다. 일반 함수는 함수를 선언할때 this에 바인딩할 (어떻게 호출되었는지에 따라) 객체가 동적으로 결정 된다. 화살표 함수는 this에 바인딩할 객체가 정적으로 결정 된다. 화살표 함수의 this는 언제나 상위 스코프의 this를 가리킨다. (Lexical this).
const obj = {
  a: 'a',
  test: function () {
    console.log(this.a);
    const arrow = () => {
      console.log(this.a);
    };
    arrow();
  },
};

const obj2 = {
  a: 'b',
};

obj.test() - 1 // a a
obj.test.call(obj2) - 2 // 
const func = obj.test;
func() - 3

그 외 용어

  • Lexical this : 언제나 상위 스코프의 this를 가리킨다.
profile
무를 심자.

0개의 댓글