The this Keyword
The this keyword in JavaScript refers to the object that is currently executing the code. Its value depends entirely on how the function is called, not where it is defined (except for arrow functions).
1. Global Context
In the global execution context (outside of any function), this refers to the global object.
- In a browser:
window. - In Node.js:
global(or empty object in modules).
console.log(this === window); // true (in browser)
2. Function Context (Simple Call)
Inside a function, the value of this depends on how the function is called.
Non-Strict Mode
If called as a simple function, this defaults to the global object (window).
function show() {
console.log(this);
}
show(); // window
Strict Mode ('use strict')
this remains undefined.
'use strict';
function show() {
console.log(this);
}
show(); // undefined
3. Method Context (Implicit Binding)
When a function is called as a method of an object, this refers to the object before the dot.
const user = {
name: "Alice",
greet() {
console.log(this.name);
}
};
user.greet(); // "Alice"
Pitfall: Losing context. If you assign the method to a variable and call it, the context is lost.
const greet = user.greet;
greet(); // undefined (or window)
4. Constructor Context (new keyword)
When a function is used as a constructor (with new), this refers to the newly created instance.
function Person(name) {
this.name = name;
}
const bob = new Person("Bob");
console.log(bob.name); // "Bob"
5. Explicit Binding (call, apply, bind)
You can force this to be a specific object.
call(obj, arg1, arg2): Invokes the function immediately.apply(obj, [args]): Invokes the function immediately (args as array).bind(obj): Returns a new function withthispermanently bound.
6. Arrow Functions (Lexical this)
Arrow functions do not have their own this. They inherit this from the surrounding scope (lexical scope) at the time they are defined. This makes them ideal for callbacks inside methods.
const group = {
title: "Developers",
members: ["Alice", "Bob"],
showList() {
// Arrow function captures 'this' from showList (which is group)
this.members.forEach((member) => {
console.log(`${this.title}: ${member}`);
});
}
};
group.showList();
// Developers: Alice
// Developers: Bob
programming/javascript/vanilla/javascript programming/functions-and-scope