The this keyword in JavaScript refers to the object that is currently executing the function.
Its value is determined by how (and where) a function is called, not where it is defined.
1️⃣ Global Context
In the global scope (outside any function or class):
console.log(this);
- In a browser,
thisrefers to thewindowobject. - In Node.js, it refers to the global object or
{}in modules.
2️⃣ Inside a Regular Function
function show() {
console.log(this);
}
show(); // 'this' -> window (in browser)
In strict mode ("use strict"), this becomes undefined.
3️⃣ Inside an Object Method
When a function is called as an object method, this refers to the object itself.
const user = {
name: "Teekam",
greet() {
console.log(`Hello, ${this.name}`);
},
};
user.greet(); // "Hello, Teekam"
4️⃣ Inside a Constructor Function
When using the new keyword, this refers to the newly created object.
function Person(name) {
this.name = name;
}
const p1 = new Person("Teekam");
console.log(p1.name); // "Teekam"
5️⃣ Arrow Functions
Arrow functions don’t have their own this.
They inherit this from their surrounding (lexical) scope.
const obj = {
name: "Teekam",
greet: () => {
console.log(this.name);
},
};
obj.greet(); // undefined (inherits from global scope)
6️⃣ With call(), apply(), and bind()
You can manually control what this refers to.
function greet() {
console.log(`Hello, ${this.name}`);
}
const user = { name: "Teekam" };
greet.call(user); // Hello, Teekam
greet.apply(user); // Hello, Teekam
const bound = greet.bind(user);
bound(); // Hello, Teekam
💡 In Short:
The value of
thisdepends on how a function is invoked:
- Global: window/global
- Method: the object
- Constructor: new instance
- Arrow function: parent scope
- call/apply/bind: explicitly set