함수와 객체(메서드)의 구분이 느슨한 자바스크립트에서 this는 실질적으로 이 둘을 구분하는 거의 유일한 기능이다.

01 상황에 따라 달라지는 this

this함수를 호출할 때 결정된다. ⇒ 어떤 방식으로 호출하느냐에 따라 달라짐.

전역 공간에서의 this

전역 공간에서 this는 전역 객체를 가리킨다. 개념상 전역 컨텍스트를 생성하는 주체가 전역 객체이다.

// 3-1 전역 공간에서의 this(브라우저 환경)
console.log(this); // Window
console.log(window); // Window
console.log(this === window); // true

Untitled

var a = 1;
console.log(a);
console.log(window.a);
console.log(this.a)

Untitled

//* 3-4 전역변수와 전역객체(2)
var a = 1;
window.b = 2;
console.log(a, window.a, this.a); // 1 1 1
console.log(b, window.b, this.b); // 2 2 2

window.a = 3;
b = 4;
console.log(a, window.a, this.a); // 3 3 3 
console.log(b, window.b, this.b); // 4 4 4

전역변수 선언과 전역객체의 프로퍼티 할당 사이 ‘삭제’ 명령은 다른 결과를 낸다.

//* 3-5 전역변수와 전역객체(3)
var a = 1;
delete window.a; // false
console.log(a, window.a, this.a); // 1 1 1

var b = 2;
delete b; // false
console.log(b, window.b, this.b); // 2 2 2

window.c = 3;
delete window.c; // true
console.log(c, window.c, this.c); // Uncaught ReferenceError: c is not defined

window.d = 4;
delete d; // true
console.log(d, window.d, this.d); // Uncaught ReferenceError: d is not defined

⇒ 전역변수를 선언하면 자바스크립트엔진이 이를 자동으로 전역객체의 프로퍼티로 할당하면서 추가적으로 해당 프로퍼티의 configurable 속성(변경 및 삭제 가능성)을 false로 정의하는 것

메서드로서 호출할 때 그 메서드 내부에서의 this