4월18일 자료도 참고하기!
🌈 this
this
는 기본적으로 전역 객체(js-window, node-global)를 가리키고, 호출하는 것이 object
이면 해당 객체를 가리킨다
- 자기자신을 호출한 녀석을
this
로 가리키게된다.
<script>
function a() {
console.log(this)
}
a()
=>> window호출 왜냐면 this는 자신을 호출한 객체를 뜻하기때문에.
즉, a() == window.a() 이니까 점 앞에를 보면된다.
</script>
객체 안에 function
<script>
let myObj = {
val1: 100,
func1: function () {
console.log(this);
}
}
myObj.func1();
--------------------------------------
let myObj = {
val1: 100,
func1: function () {
console.log(this);
}
}
let test = myObj.func1;
test()
</script>
function 안에 function
<script>
function a(){
console.log(this)
function b(){
console.log(this)
function c(){
console.log(this)
}
c()
}
b()
}
a()
</script>
정리
- 전역공간의 this는 window(node는 global)
- 메서드로 호출한 경우 this는 멤버접근연산자 앞에 객체
- 함수로 호출할 경우 this는 window(node는 global)
- 화살표 함수의 경우 this는 상위스코프
- 생성자 함수의 경우 this는 인스턴스
- 콜백함수의 경우 this가 다르게 동작 할 수 있음