기존의 방법으로 사용된 this context
const myObj = { runTimeout(){ setTimeout(function(){ this.printData(); }.bind(this), 2000); }, //여기서 bind를 통해서 window 내의 printData를 찾는 것이 아닌, myObj 내에서 찾도록 만들어준다. printData(){ console.log("Hello ES6!"); } }
Arrow funciton의 적용
const myObj = { runTimeout(){ setTimeout(() => { console.log(this === window); this.printData(); }, 2000); }, //bind가 없어지고, Arrow가 포함되는 이 때에는 this !== window 가 false가 되면서, "Hello ES6!"가 찍힌다. printData(){ console.log("Hello ES6!"); } }
Arrow function this context의 활용
//어떤 div 태그 내에 testing 이라는 문자열이 있다고 가정 const el = document.querySelector("div"); const myObj = { register(){ el.addEventListener("click", (event) => { this.printData(event.target); }); }, printData(el){ console.log('Clicked!', el.innerText); } } myObj.register(); //HTML 상의 testing 글자를 클릭하면, "Clicked!"와 함께 "testing"이 event.target.innerText의 값으로서 찍힐 것이다.
_.each and _.reduce - Lodash (0) | 2019.04.22 |
---|---|
express로 구현하는 실습 문제 - Javascript, NodeJS (0) | 2019.04.21 |
Tagged Template literals - HTML, Javascript ES6 (0) | 2019.04.19 |
Set으로 로또 추첨기 만들기 - Javascript ES6 (0) | 2019.04.19 |
WeakMap으로 class의 instance 변수 보호하기 - Javascript ES6 (0) | 2019.04.19 |
댓글 영역