#TIL16

전혜린·2021년 8월 9일
0

Today I Learned

목록 보기
21/64

this

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

const hyerin = {
name: 'hyerin',
normal: function () {
console.log(this.name)
},
arrow: () => {
console.log(this.name)
}
}
hyerin.normal() // hyerin
hyerin.arrow() // undefined

  • 점 표기법을 이용해 hyerin 내부의 normal 메소드 실행
  • 호출위치: 호출 위치에서 메소드가 딸려있는 앞의 객체데이터 hyerin가 곧 this
  • 화살표 함수에서의 this는 호출 위치와 전혀 관계없이 이것이 선언될 때 this가 무엇인지 충분히 알 수 있음

const amy = {
name: 'amy',
normal: hyerin.normal,
arrow: hyerin.arrow
}
amy.normal() // amy
amy.arrow() // undefined

  • normal: hyerin.normal은 호출하는 개념이 아니라 normal 부분에 있는 데이터(function () { console.log(this.name)}) 함수 자체가 amy의 normal에 할당되는 구조
  • arrow: hyerin.arrow는 hyerin의 데이터 부분 자체가 amy의 arrow에 할당되는 구조
  • amy.normal()는 호출 위치에서 정의 즉, 호출이 될 때 연결되어져 있는 객체는 amy이기 때문에 amy가 곧 this이므로 this부분의 name이 출력됨

생성자함수

function User(name) {
this.name = name
}
User.prototype.normal = function () {
console.log(this.name)
}

User.prototype.arrow = () => {
console.log(this.name)
}

const jeonhyerin = new User('jeonhyerin')
// new라는 키워드로 생성자 함수 실행하면 그것이 곧 객체데이터

jeonhyerin.normal() // jeonhyerin
jeonhyerin.arrow() // undefined

타이머 함수

const timer = {
name: 'hyerin!!',
timeout: function () {
// setTimeout(함수, 시간)
setTimeout(() => {
console.log(this.name)
}, 2000)
}
timer.timeout()

  • this.name을 timer라는 객체데이터의 name부분을 지칭해서 출력하기를 원한다면 timeout이라는 타이머함수의 콜백으로 화살표 함수 써야함
  • 화살표 함수를 감싸고 있는 추가적인 함수범위가 있기 때문에 함수범위에서 this가 정의되는 것이고 그 함수부분의 this는 일반함수가 정의된 timer라는 객체데이터를 가르키기 때문에 this = timer
  • setTimeout, setInterval 타이머함수 사용시 callback으로 일반함수보다는 화살표 함수를 사용하는 것이 활용도가 높음
  • 화살표 함수 사용시에는 this 라는 것이 자바스크립트에서 setTimeout이라는 함수의 이미 어딘가에서 정의 되어진 것이 아닌 명확하게 우리가 작성한 특정한 범위에서 this가 정의될 수 있도록 만들어 줄 수 있기 때문
profile
코딩쪼아

0개의 댓글