The this
keyword in JavaScript refers to the object that is executing the current function. Its value depends on where and how it is used.
In the global execution context (outside of any function), this
refers to the global object. In a web browser, this is window
.
console.log(this); // In a browser, this refers to the window object
In a regular function, this
refers to the global object (in non-strict mode) or undefined
(in strict mode).
function showThis() {
console.log(this); // In non-strict mode, this refers to the global object (window in browsers)
}
showThis();
In strict mode, this
is undefined
.
"use strict";
function showThis() {
console.log(this); // In strict mode, this is undefined
}
showThis();
When a function is called as a method of an object, this
refers to the object.
let person = {
name: 'John',
greet: function() {
console.log(this); // this refers to the person object
}
};
person.greet();
When a function is used as a constructor (with the new
keyword), this
refers to the newly created object.
function Person(name) {
this.name = name;
}
let person1 = new Person('John');
console.log(person1.name); // Output: John
Arrow functions do not have their own this
context. Instead, they inherit this
from the parent scope at the time they are defined.
let person = {
name: 'John',
greet: function() {
setTimeout(() => {
console.log(this); // this refers to the person object because arrow functions inherit this from the parent scope
}, 1000);
}
};
person.greet();
In HTML event handlers, this
refers to the element that received the event.