함수 실행 시 호출(invocation) 방법에 의해 결정되는 특별한 객체. 비엄격 모드에서 항상 객체를 참조하며, 엄격 모드에서는 어떠한 값도 될 수 있음. 영어의 '지시대명사'의 기능과 동일해 보임. 실행되는 맥락(execution context)에 따라 따르게 결정. 화살표 함수와는 완전 상극이므로 같이 쓰면 안된다.
user.printName() -> user가 this
user.company.printName() -> user.company가 this
function foo() {
console.log("foo's this: ", this); // window
function bar() {
console.log("bar's this: ", this); // window
}
bar() // Window
}
foo() // Window
method의 내부 함수도 this 전역객체에 바인딩 됨.
var obj1 = {
name: 'Lee',
sayName: function() {
console.log(this.name);
}
}
var obj2 = {
name: 'Kim'
}
obj2.sayName = obj1.sayName;
obj1.sayName(); // lee
obj2.sayName(); // kim
일반 함수를 호출하면 this는 전역객체에 바인딩되지만 new 연산자와 함께 생성자 함수를 호출하면 this는 생성자 함수가 암묵적으로 생성한 빈 객체에 바인딩된다.
function Person(name) {
this.name = name;
}
var me = new Person('Park');
console.log(me); // {name: "Park"}
new 키워드를 이용한 생성자(class),
.call /.apply 호출: 첫번째 인자로 전달된 객체