Udemy에서 React 기초강의를 들으면서 기본기를 단단히 해야겠다는 마음을 먹었습니다.
그래서 구매한 강의는 바로
지금부터 React 학습에 필수적인 JS지식을 정리해보겠습니다!!! 🔥
JS ES6부터 등장한 화살표 함수 표현법에 대해 알아봅시다.
//es 6이전
function test(a){
return a + 100;
}
//es 6이후 arrow function
const test = (a) => {
return a + 100;
}
//arrow function 간략히(코드가 1줄일때)
const test = a => a + 100
콜백함수에서도 적용하며 좀 더 간결한 표현이 가능합니다.
var numbers = [1,2,3];
var squaredNum = numbers.map(function(x){ return x*x});
console.log(squaredNum); //[1,4,9]
var numbers = [1,2,3];
var squaredNum = numbers.map(x => x*x);
console.log(squaredNum); //[1,4,9]
//es 6이전
var fruitShop = {
name: 'apple',
func: function(){
console.log(this) //Object
console.log(this.name) //apple
setTimeout(function(){
console.log(this === window) //true
}
}
}
fruitShop.func();
첫번째 this => 자신을 호출하는 객체에 바인딩이 됩니다.
두번째 this => 'apple' 제대로 출력이 됩니다.
세번째 this(중요) => 전역객체(window)에 바인딩이 됩니다.
함수의 내부함수 및 콜백함수의 this는 전역객체에 바인딩이 됨을 알 수 있습니다.
arrow function으로 가볼까요?
//es 6이후
var fruitShop = {
name: 'apple',
func: function(){
setTimeout(()=>{
console.log(this === window) //false
console.log(this.name) // apple
})
}
}
fruitShop.func()
func의 내부함수를 arrow function으로 작성하면 this는 자신을 감싸는 함수의 this에 바인딩이 됨을 알 수 있습니다.
즉, arrow function은 자신을 포함하는 외부 scope에서 this를 계승받는다입니다.