[JS] Arrow function

Jay ·2022년 10월 12일
0

1. Arrow function?

function 키워드 대시 화살표를 사용한 함수를 정의.

ES6에서 추가되었음.

콜백 함수 내부에서 this가 전역 객체를 가리키는 문제를 해결하기 위해 설계.

선언문으로 정의할 수 없고 표현식으로 정의해야 함.

표현식 vs 문

const arrow = () => const x =1;
// X, statement를 반환할수 없음.

const arrow = () => { return const x = 1; };
// O

const create = (id, content) => {id, content};
// 객체반환 어떻게?

2. Arrow function vs function

1) 인스턴스를 생성할 수 없음

const foo = () => {};
Foo.hasOwnProperty('prototype'); // false  

2) 중복된 매개변수 이름 선언 불가능
-일반함수는 중복선언이 가능하긴 하지만, stric 모드에선 불가능

3) 자체의 this, arguments, super, new.target 바인딩을 갖지 않는다.
(Lexical this : 스코프체인을 통해 상위 스코프의 것을 참조)

function foo(){
  return {
    first: 'hyojin',
    last: 'lee',
    asyncFn: function(){
    
      console.log(this); // {first: "hyojin", last: "lee", setTimeFunc: ƒ}
      
      setTimeout(() => {
        console.log(this.first);
      }, 1000);
    }
  }
}
let bar = foo();

3. No Arrow function

1) 객체의 메소드로 정의

// Bad
const person = {
  name: 'Lee',
  sayHi: () => console.log(`Hi ${this.name}`)
};
person.sayHi(); // Hi undefined

2) 프로토타입의 메소드로 정의

// Bad
const person = { // 모든 객체는 기본적으로 Object객체에 프로토타입 체이닝 되어있다.
  name: 'Lee',
};
 
Object.prototype.sayHi = () => console.log(`Hi ${this.name}`);
 
person.sayHi(); // Hi undefined

3) 생성자 함수로 사용 불가능

  • 화살표함수는 prototype 프로퍼티를 가지지 않음.

4) addEventListener

References

https://inpa.tistory.com/entry/JS-%F0%9F%93%9A-%EC%9E%90%EB%B0%94%EC%8A%A4%ED%81%AC%EB%A6%BD%ED%8A%B8-%ED%99%94%EC%82%B4%ED%91%9C-%ED%95%A8%EC%88%98-%EC%A0%95%EB%A6%AC

profile
Jay입니다.

0개의 댓글