함수를 호출할 때 생성되는 실행 컨텍스트 객체를 말한다.
this는 실행 컨텍스트가 생성될 때 결정되며, 함수가 호출되는 방식에 따라 다르게 바인딩된다.
전역에서 this를 참조하면 브라우저에서는 전역(window) 객체를 가리킨다.
console.log(this); //window
함수 내부에서 this를 사용하면, 전역(window) 객체를 가리킨다.
non-strict mode 에서는 전역 객체를, strict mode 에서는 undefined
function foo() {
console.log(this); //window
}
foo();
객체의 메소드로 호출되었을 경우, this는 그 객체를 가리킨다.
const obj = {
name: "Peter",
funcD: () {
console.log(this.name);
}
}
obj.funcD();
//Peter
new 키워드를 사용하여 함수를 호출하면, 새로운 객체가 생성되면 this가 그 객체를 가리킨다.
function Person(name) {
this.name = name;
}
const me = new Person('Alice');
console.log(me.name); // "Alice"
****
.call(), .apply(), .bind() 메서드를 사용하면 this를 명시적으로 지정할 수 있다.
function greet() {
console.log(this.name);
}
const user = { name: 'Bob' };
greet.call(user); // "Bob"
greet.apply(user); // "Bob"
const boundGreet = greet.bind(user);
boundGreet(); // "Bob"
call()과 apply() 는 즉시 실행하며, 첫 번째 인자로 this를 지정한다.bind()는 새로운 함수를 반환하여 나중에 실행할 수 있도록 한다.화살표 함수의 경우, this를 바인딩하지 않고 선언된 위치에서 this를 상속한다.
즉 자신을 감싸고 있는 상위 스코프의 this를 그대로 사용한다.
const obj = {
name: "Alice",
funcD: () => {
console.log(this.name);
},
};
obj.funcD();
//undefined
const obj = {
name: "Alice",
funcD: function () {
setTimeout(() => {
console.log(this.name);
}, 1000)
},
};
obj.funcD();
//Alice
상위 스코프인 funcD 함수의 this를 상속받는다.
funcD는 obj 객체의 메소드이기 때문에, this는 ****obj 객체에 바인딩되어있다.
DOM
addEventListener()의 경우,this는 e.currentTarget과 같다.
| 호출 방식 | this 값 |
|---|---|
| 전역 실행 | window (브라우저) / global (Node.js) |
| 일반 함수 호출 | window (strict mode에서는 undefined) |
| 메서드 호출 | 호출한 객체 |
| 생성자 함수 호출 | 새로 생성된 객체 |
| call / apply / bind 사용 | 명시적으로 지정된 객체 |
| 화살표 함수 | 상위 스코프의 this |