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/
'자바스크립트' 카테고리의 다른 글
크롬 디버깅 (0) | 2020.11.20 |
---|---|
엄격 모드 (0) | 2020.11.20 |
Date 객체 (0) | 2020.11.18 |
||, && 연산자 (0) | 2020.11.17 |
좋은 코드를 위한 전역 변수의 최소화 (0) | 2020.11.15 |