자바스크립트
this
devjones
2020. 11. 18. 21:13
this는 현재 실행 문맥이다.
'실행문맥'이란 말은 호출자가 누구냐는 것과 같다.
alert(this === window) // true, 호출자는 window
const caller = {
f : function() {
alert(this === window)
}
}
caller.f(); // false, 호출자는 caller 객체
strict-mode에서는 전역 객체냐 일반 객체냐에 따라 함수내부에 this의 결과가 다르다는 차이가 있다. 그러나 이문제 또한 window를 함수 호출 앞에 붙여주면 해결된다.
function nonStrictMode() {
return this;
}
function strictMode() {
'use strict'
return this
}
console.log(nonStrictMode()); // window
console.log(strictMode()); // undefined
console.log(window.strictMode); // window
출처:
blueshw.github.io/2018/03/12/this/