This Keyword
In JavaScript, the this keyword refers to the execution context, which is determined by how a function is called, not where it's defined.
Its value can change depending on the context (global, object, strict mode, arrow functions, etc.).
Let's see 6 general contexts where this is used.
Global Context
In the global context, this refers to the global object.
In browsers it is the window object. In Node.js it is the global object.
console.log(this); // Browser: window object
console.log(this); // Node.js: global object
Function Context
In a regular function call, this depends on whether you're in strict mode:
- Non-strict mode: this refers to the global object
- Strict mode: this is undefined
function showThis() {
console.log(this);
}
showThis(); // Window (non-strict) or undefined (strict)
Method Context
When a function is called as a method of an object, this refers to the object:
const person = {
name: 'Alice',
greet: function() {
console.log(`Hello, I'm ${this.name}`);
}
};
person.greet(); // "Hello, I'm Alice" - `this` refers to `person`
Arrow Functions
Arrow functions don't have their own this context. They inherit this from the parent scope:
const user = {
name: "John",
greet: () => {
console.log(this.name);
},
};
user.greet(); // undefined (inherited `this` from global scope)
Constructor Context
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;
}
const bob = new Person('Bob');
console.log(bob.name); // "Bob"
Event Handler Context
In event handlers, this refers to the element that triggered the event:
document.getElementById('myButton').addEventListener('click', function() {
console.log(this); // The button element
});