상세 컨텐츠

본문 제목

Arrow funciton의 this context - Javascript ES6

Programming/Concept

by 쌩우 2019. 4. 19. 17:46

본문

기존의 방법으로 사용된 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의 값으로서 찍힐 것이다.


관련글 더보기

댓글 영역