Understanding this in JavaScript (in Different Contexts)


What is this?

In JavaScript, this refers to the object that is executing the current function. The value of this depends on how a function is called — not where it is defined.



1. Global Context

console.log(this); // In browser: Window object
  • In the global scope (non-strict mode), this refers to the global object:
  • In browser: window
  • In Node.js: global


2. Inside a Regular Function

function show() {
console.log(this);
}
show(); // In browser: Window (undefined in strict mode)
  • In non-strict mode, this is the global object.
  • In strict mode, this is undefined.


3. Inside an Object Method

const person = {
name: "Alice"
,
greet: function () {
console.log("Hi, " + this.name);
},
};
person.greet(); // Output: Hi, Alice
 Here, this refers to the object (person) that calls the method


4. Arrow Functions

const person = {
name: "Bob",
greet: () => {
console.log("Hi, " + this.name);
},
};
person.greet(); // Output: Hi, undefined

Arrow functions do not have their own this.

They inherit this from their surrounding (lexical) scope.



5. In Event Handlers

<button onclick="console.log(this)">Click Me</button>
  • this refers to the DOM element (the button).


Or using JavaScript:

document.querySelector("button").addEventListener("click", function ()
{
console.log(this); // the button element
});


6. With call(), apply(), and bind()

function greet() {
console.log("Hello, " + this.name);
}
const user = { name: "Emma" };
greet.call(user); // Hello, Emma
greet.apply(user); // Hello, Emma
const boundGreet = greet.bind(user);
boundGreet(); // Hello, Emma

These methods manually set this.



7. In Classes

class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(this.name + " makes a sound. ");
}
}
const dog = new Animal("Rex");
dog.speak(); // Rex makes a sound.
  • this refers to the instance of the class.


8. this Inside setTimeout or setInterval

const obj = {
name: "Timer",
start: function () {
setTimeout(function () {
console.log(this.name); // undefined or Window (global)
}, 1000);
},
};
obj.start();


Solution using arrow function:

start: function () {
setTimeout(() => {
console.log(this.name); // Timer
}, 1000);
}

Arrow functions solve this issues in callbacks.



Summary Table

Context this refers to…
Global scope Global object (Window in browser)
Regular function Global (non-strict), undefined (strict)
Object method The object that called the method
Arrow function Lexical parent’s this
Event handler (HTML/DOM) The DOM element triggering the event
Class method The instance of the class
call, apply, bind The manually set object