javaScript(this)

Dev_Go·2022년 6월 25일
0

모던 자바스크립트

목록 보기
11/37
post-thumbnail

this


실행 컨텍스트(global, function 또는 eval)의 프로퍼티는 비엄격 모드에서 항상 객체를 참조하며, 엄격 모드에서는 어떠한 값이든 될 수 있습니다.

일반함수와 화살표함수의 this 차이

  • 일반(Normal) 함수는 호출 위치에서 따라 this 정의!
  • 화살표(Arrow) 함수는 자신이 선언된 함수 범위에서 this 정의!

일반함수에서 this

const gaeng = {
  name: 'Gaeng',
  nomer: function () {
    console.log(this.name)
  },
  arrow: () => {
    console.log(this.name)
  }
}
gaeng.nomer()
gaeng.arrow()

const amy = {
  name: 'Amy',
  nomer: gaeng.nomer,
  arrow: gaeng.arrow
}
amy.nomer()
amy.arrow()

heropy.nomer()를 호출했을 때 nomer에서 thisgaeng이다.
console.log(this.name) = gaengname부분을 꺼내서 사용하라는 말이기 때문에 console창에 Gaeng이 출력되는 것이다.

amy.nomer()를 호출했을 때 nomer에서 thisamy이다.
nomergaeng.nomer = function () {console.log(this.name)} 이 부분을 가져오라는 뜻 이기때문에 console.log(this.name) = amyname부분을 꺼내서 사용하라는 말이다. 그러므로 console창에 Amy가 출력되는 것이다.

화살표함수에서 this

const timer = {
  name: 'Gaeng',
  timeout: function () {
    setTimeout(() => {
      console.log(this.name)
    }, 2000)
  }
}
timer.timeout()

timer.timeout()를 호출했을 때 timeout 안에 함수 범위에서 this가 정의되는 것이고 그 함수 부분에서 this는 곧 일반함수가 정의된 timer라는 객체데이터를 가르키기 때문에 여기서 this = timer가 되는 것입니다.

console.log(this.name) = timername부분을 꺼내서 사용하라는 말이다. 그러므로 console창에 Gaeng가 출력되는 것이다.

profile
프론트엔드 4년차

0개의 댓글