console.log(this)
this값은 기본적으로는 window 객체입니다.
window는 모든 전역변수, 함수, DOM을 보관하고 관리하는 전역객체이다.
function main() {
console.log(this);
}
main();
this값은 함수를 호출한 객체이기에 전역에서와 마찬가지로
Window를 출력한다.
"use strict";
function main() {
console.log(this);
}
main();
strict mode는 자바스크립트 코드를 실행할 때 발생하는 일부 문제를 잡고 오류를 줄이기 위한 특별한 모드이다.
정상 출력을 원하면 window.main()을 사용해야 한다.
const object = {
name: '객체',
main: function () {
console.log(this);
},
};
object.main()
this값은 함수를 호출한 객체이기에 main함수를 호출한 object객체를 출력한다.
function main() {
console.log(this);
}
const object = {
name: '객체',
subObject: {
name: '하위객체',
main,
}
};
object.subObject.main();
const btn = document.querySelector("#btn");
btn.addEventListener("click", function () {
console.log(this);
});
이벤트 핸들러에서 this는 이벤트를 받는 HTML 요소를 가리킨다.
const object = {
name: '객체',
showTime(s) {
setTimeout(()=>{
console.log(this.name);
}, s);
}
};
object.showTime(10);
객체
화살표함수에서의 this는 상위 실행컨텍스트의 this를 가리킨다. setTimeout의 상위 실행컨텍스트는 showTime이다. showTime은 객체 메소드 에서 사용되었기에 this는 object를 가리킨다.