The keyword this in JavaScript behaves differently depending on where and how it is used. Understanding its value in various contexts is essential for writing correct and predictable code.

💡 Key Concept
this refers to the object that is executing the current function.
1. Global Context
Outside of any function, this refers to the global object.
- In browsers, the global object is
window. - In Node.js, it is
global.
📌 Deep Dive: this in Global Scope
console.log(this === window); // true (in browser)
2. Function Context
Inside a regular function, this depends on how the function is called:
| Call Type | Value of this |
|---|---|
| Simple function call | undefined in strict mode, window otherwise |
| Method call (object.function()) | Object owning the method |
📌 Deep Dive: this in Function vs Method
function show() {
console.log(this);
}
const obj = {
show: show
};
show(); // In strict mode: undefined; otherwise global object
obj.show(); // obj
[object Object]
3. Arrow Functions
Arrow functions do not have their own this. Instead, they inherit this from the surrounding (lexical) context.
📌 Deep Dive: Arrow Function this
const obj = {
value: 42,
arrowFunc: () => {
console.log(this.value);
},
regularFunc() {
const innerArrow = () => console.log(this.value);
innerArrow();
}
};
obj.arrowFunc(); // undefined (this from global scope)
obj.regularFunc(); // 42 (this from obj)
42
4. Constructor Functions and Classes
When a function is called with new, this refers to the newly created object.
📌 Deep Dive: this in Constructors
function Person(name) {
this.name = name;
}
const p = new Person("Alice");
console.log(p.name); // Alice
5. Explicit Binding: call, apply, and bind
You can explicitly set this using call, apply, or bind.
📌 Deep Dive: Explicitly setting 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
Bob
Bob
⚠️ Common Pitfall
Using this inside nested functions often results in unexpected this values because each function defines its own this. Use arrow functions or bind to maintain the proper context.
Summary Table
this Value in Different Contexts| Context | this Value |
|---|---|
| Global scope | Global object (window in browsers) |
| Regular function call | undefined (strict mode) or global object |
| Method call | The object owning the method |
| Arrow function | Lexical this (from surrounding context) |
Constructor (with new) | The new instance object |
Explicit binding (call, apply, bind) | Object passed as first argument |
Quick Knowledge Check
Test what you just learned
Question 1 of 2
What does this refer to inside an arrow function?
Question 2 of 2
What happens to this when a function is called with new?
Loading results...