Arrow function 문법
- ES6에 도입된 함수 선언 방법
- 화살표 (=>) 키워드를 사용하여 간결한 코드 작성 가능
- 함수 표현식 (익명 함수) 로만 사용 가능
const printLog = () => {
console.log('no paramter!');
}
const sqare = n => { return n * n };
const sqare = n => n * n;
const add = (n1, n2) => {
return n1 + n2;
}
this 키워드
1. ES5 의 this
1. function 실행 시, 전역 객체 (window)
function myFunc() {
this;
}
2. method (객체 내부의 속성으로 정의된 function) 실행 시, method를 소유하고 있는 객체
const myObj = {
myMethod : () => {
this;
}
};
3. 생성자 실행 시, 생성된 인스턴스
function myConstructor() {
this;
}
var newObj = new myConstructor();
ES6 Arrow function 의 this
- 상위 환경의 this를 그대로 계승
- 한번 할당 되면 절대 바뀌지 않음 (Lexical this)
function objFunc() {
console.log('objFunc 의 num : ', this.num);
return {
num: 999,
arrowFunc: () => console.log('Arrow func 의 num : ', this.num);
};
}
objFunc.call({num: 7}).arrowFunc();
- arrowFunc의 this는 상위 환경인 objFunc의 this를 따라감
결론
- ES5 의 this는 실행되고 있는 scope에 따라 다른 값을 참조한다.
- ES6 Arrow function 의 this는 자신의 상위 환경의 this 를 그대로 따르기 때문에 this의 scope가 바뀌지 않는다.
참고