써치킴의 우당탕탕 개발 블로그

[JS Essentials][Ch2][클래스] this 본문

파도파도 나오는 JavaScript

[JS Essentials][Ch2][클래스] this

써치킴 2022. 1. 28. 18:41

this

  • 일반(Normal) 함수호출 위치에 따라 this 정의
  • 화살표(Arrow) 함수자신이 선언된 함수에서 함수 범위에서 this 정의
const searchkim = {
  name : 'SearchKim',
  normal : function () {    // 익명의 일반함수
    console.log(this.name);
  },
  arrow : () => {           // 화살표 함수
    console.log(this.name);
  }
}
// () : 호출
// 일반함수는 searchkim이라는 객체가 this이기 때문에 this의 name이 콘솔에 표출
searchkim.normal();   // 객체의 메소드 실행
// undefined 표출
searchkim.arrow();    // 객체의 메소드 실행 


const amy = {
  name : 'Amy',
  // searchkim 객체의 normal 데이터 -> 즉, normal의 일반함수 자체가 amy의 normal에 할당
  normal : searchkim.normal,   
  // searchkim 객체의 arrow 데이터 -> 즉, arrow의 화살표함수 자체가 amy의 arrow에 할당
  arrow : searchkim.arrow
}

amy.normal();
amy.arrow();

function User(name) {    // 생성자 함수
  this.name = name;
}
User.prototype.normal = function () { // 메소드(일반 함수 할당)
  console.log(this.name);
}
User.prototype.arrow = () => {        // 메소드(화살표 함수 할당)
  console.log(this.name);
}

// 생성자 함수를 실행한 객체 데이터(search)
const search = new User('SearchKim');

search.normal();    // SearchKim 표출
// 자신이 선언된 함수에서 this가 정의되기 때문에 화살표 함수 내(범위)에 참조할 name이 보이지 않음
search.arrow();     // undefined 표출

const timer = {
  name : 'Searchkim',
  timeout : function () {
    // setTimeout(함수, 시간)
    // 자신이 선언된 함수 범위에 name이 있기 때문에 콘솔에 정상적으로 표출됨
    setTimeout(() => {    
      console.log(this.name);
    } , 2000);
  }
}
timer.timeout();

따라서 setTimeout, setIntervel은 화살표 함수를 사용하는 것을 권장한다!

Comments