The this keyword in JavaScript is a special identifier that refers to the execution context of a function. Its value depends on how and where the function is called, not where it is defined.

💡 Key Concept
this is determined at runtime based on the invocation context, not lexical scope.
Common this Contexts
this is set| Context | Value of this |
|---|---|
| Global function call | window (browser) or global (Node.js) or undefined in strict mode |
| Method call (object property) | The object owning the method |
Constructor function (called with new) | The newly created object |
| Arrow function | Lexically inherited from enclosing scope |
Explicit binding (call, apply, bind) | Set explicitly to the first argument of these methods |
1. Global Context
When a function is called in the global scope, this refers to the global object (unless in strict mode).
📌 Deep Dive: Global this
function show() {
console.log(this);
}
show();
2. Object Method
When called as a method, this refers to the object before the dot.
📌 Deep Dive: Method this
const user = {
name: 'Alice',
greet() {
console.log(this.name);
}
};
user.greet();
3. Constructor Functions
When a function is called with new, this points to the newly created object.
📌 Deep Dive: Constructor this
function Person(name) {
this.name = name;
}
const p = new Person('Bob');
console.log(p.name);
4. Arrow Functions
Arrow functions do NOT have their own this. Instead, they inherit this from the surrounding lexical scope.
📌 Deep Dive: Arrow Function this
const obj = {
name: 'Carol',
regular() {
console.log(this.name);
},
arrow: () => {
console.log(this.name);
}
};
obj.regular(); // Carol
obj.arrow(); // undefined (or global this.name)
undefined
⚠️ Arrow Function Gotcha
Do not use arrow functions as object methods if you need to access the object via this because they don't have their own this.
5. Explicit Binding
You can explicitly set the value of this using call, apply, or permanently bind with bind.
📌 Deep Dive: Explicit this Binding
function showName() {
console.log(this.name);
}
const user = { name: 'Dave' };
showName.call(user); // Dave
const bound = showName.bind(user);
bound(); // Dave
Dave
💡 Summary
thisdepends on call-site, not function definition.- Arrow functions inherit
thislexically. - Use
call,apply, orbindto changethisexplicitly. - Be cautious with
thisinside event handlers or callbacks.
Quick Knowledge Check
Test what you just learned
Question 1 of 2
What does this refer to inside a regular function called as a method of an object?
Question 2 of 2
Which statement about arrow functions and this is true?
Loading results...