[javascript] this

찐찐·2022년 3월 27일
0

이 게시글은 여러 가지 글을 참고하여 작성됐으며, 틀린 부분이 많을 수도...

JS의 this는 다른 언어와 다르게 작동한다.

  • 즉 우리에게 익숙한 Java의 this는 자기 자신을 참조하는 것이지만, JS에서는 그렇지 않다.
  • JS에서 this의 값은 함수를 호출한 방식에 따라 결정된다.
  • 또한 엄격 모드와 비엄격 모드로도 나뉜다.

this in a method

object method로 동작할 때, this해당 object를 참조한다.

this Alone

this가 global scope에서 혼자 사용된다면, global object를 참조한다.

  • 엄격 모드에서도 동일하게 동작한다.

this in a function

this가 function 내부에서 사용된다면,

  • 일반(비엄격) 모드에서는 global object를 참조한다.
  • 엄격 모드에서는 undefined이다. (엄격 모드에서는 defualt binding을 허용하지 않는다.)

명시적인 function binding

call()apply()는 미리 정의된 JS 함수이다.

function borrowing

bind()를 사용하면 다른 object에서 method를 빌려올 수 있다.

// 예시
const person = {
  firstName:"John",
  lastName: "Doe",
  fullName: function () {
    return this.firstName + " " + this.lastName;
  }
}

const member = {
  firstName:"Hege",
  lastName: "Nilsen",
}

let fullName = person.fullName.bind(member);

this in a event handler

HTML Event Handler에 사용되는 경우, 해당 event가 적용되는 HTML element를 참조한다.


참고

profile
백엔드 개발자 지망생

0개의 댓글