[basics] ES6 Arrow function 문법과 this 키워드

Jinbro·2022년 9월 15일
0

basics

목록 보기
6/8

Arrow function 문법

  • ES6에 도입된 함수 선언 방법
  • 화살표 (=>) 키워드를 사용하여 간결한 코드 작성 가능
  • 함수 표현식 (익명 함수) 로만 사용 가능
// 파라미터 없는 경우
const printLog = () => {
	console.log('no paramter!');
}

// 파라미터 1개인 경우, 소괄호 생략 가능
const sqare = n => { return n * n };

// 한 줄에 작성 가능한 경우, 중괄호 생략 가능
const sqare = n => n * n;

// 파라미터 2개 이상인 경우
const add = (n1, n2) => {
	return n1 + n2;
}

this 키워드

1. ES5 의 this

1. function 실행 시, 전역 객체 (window)

function myFunc() {
	this; // window
}

2. method (객체 내부의 속성으로 정의된 function) 실행 시, method를 소유하고 있는 객체

const myObj = {
	myMethod : () => {
      this; // myObj
    }
};

3. 생성자 실행 시, 생성된 인스턴스

function myConstructor() {
	this; // newObj
}
var newObj = new myConstructor();

ES6 Arrow function 의 this

  • 상위 환경의 this를 그대로 계승
  • 한번 할당 되면 절대 바뀌지 않음 (Lexical this)
function objFunc() {
	console.log('objFunc 의 num : ', this.num); // 7
	return {
		num: 999,
		arrowFunc: () => console.log('Arrow func 의 num : ', this.num); // 7
	};
}

objFunc.call({num: 7}).arrowFunc(); // objFunc 의 this 오버라이딩
  • arrowFunc의 this는 상위 환경인 objFunc의 this를 따라감

결론

  • ES5 의 this는 실행되고 있는 scope에 따라 다른 값을 참조한다.
  • ES6 Arrow function 의 this는 자신의 상위 환경의 this 를 그대로 따르기 때문에 this의 scope가 바뀌지 않는다.

참고

profile
자기 개발 기록 저장소

0개의 댓글