Programming Skills/es6
es6 - Arrow function
Ideveloper2
2018. 4. 14. 18:15
es6 - Arrow function
| Arrow function 활용
let newArr = [1,2,3,4,5].map(function(value){
return value * 2;
});아래와 위는 같다.(syntax 유지)
let newArr = [1,2,3,4,5].map((value)=> value * 2);배열 map, reduce,filter 함수의 콜백에서 arrow function이 자주 사용될 수 있다.
| Arrow function 의 this context
arrow function의 this context 유지 속성 덕분에, bind 함수를 쓸 필요가 없어지게 된다.
const myObj ={
runTimeout(){
setTimeout(function(){
this.printData();
},200);
},
printData(){
console.log('hi');
}
}위는 오류가 난다. this가 window 객체를 가리키게 되기 때문이다.따라서 myObj 객체의 printData를 호출할수 없다. 따라서 아래와 같이 binding을 해줘야만 한다.
const myObj ={
runTimeout(){
setTimeout(function(){
this.printData();
}.bind(this),200);
},
printData(){
console.log('hi');
}
}arrow function은 this의 context를 유지하고 있어서 아래와 같이 실행이 가능하다.
const myObj ={
runTimeout(){
setTimeout(()=>{
this.printData();
},200);
},
printData(){
console.log('hi');
}
}Ex2)
arrow function의 this context 유지 속성 때문에 아래의 코드도 가능하게 된다.
const el =document.querySelector("p");
const myObj ={
register(){
el.addEventListener("click",(evt)=>{
this.printData(evt.target);
});
},
printData(el){
console.log('clicked!', el.innerText);
}
}| 마치며
react에서 클래스형 컴포넌트의 이벤트메서드를 작성할때, arrow function을 쓰면 binding을 해줄 필요가 없었던 이유도 알게 되었다. 예전엔 그 이유도 모르고 쓰고 있었다..ㅎ