이 게시글은 여러 가지 글을 참고하여 작성됐으며, 틀린 부분이 많을 수도...
JS의 this
는 다른 언어와 다르게 작동한다.
this
는 자기 자신을 참조하는 것이지만, JS에서는 그렇지 않다.this
의 값은 함수를 호출한 방식에 따라 결정된다.this
in a methodobject method로 동작할 때, this
는 해당 object를 참조한다.
this
Alonethis
가 global scope에서 혼자 사용된다면, global object를 참조한다.
this
in a functionthis
가 function 내부에서 사용된다면,
undefined
이다. (엄격 모드에서는 defualt binding을 허용하지 않는다.)call()
과 apply()
는 미리 정의된 JS 함수이다.
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 handlerHTML Event Handler에 사용되는 경우, 해당 event가 적용되는 HTML element를 참조한다.