Home
JavaScript
How `this` behaves in JavaScript
April 24, 2024
1 min

Table Of Contents

01
๐Ÿ”น What is this?
02
๐Ÿ”ธ 1. Global Context
03
๐Ÿ”ธ 2. Inside a Regular Function
04
๐Ÿ”ธ 3. Inside an Object Method
05
๐Ÿ”ธ 4. Arrow Functions & this
06
๐Ÿ”ธ 5. Inside Class Methods
07
๐Ÿ”ธ 6. In Event Listeners

๐Ÿ”น What is this?

In JavaScript, this refers to the execution context โ€” or how a function is called, not where itโ€™s defined.


๐Ÿ”ธ 1. Global Context

console.log(this); // In browser: window; In Node.js: {}

๐Ÿ”ธ 2. Inside a Regular Function

function show() {
console.log(this);
}
show(); // In non-strict mode: window (or global), in strict mode: undefined

๐Ÿ”ธ 3. Inside an Object Method

const user = {
name: "Daniel",
greet() {
console.log(this.name);
}
};
user.greet(); // "Daniel"

In object methods, this refers to the object the method is called on.


๐Ÿ”ธ 4. Arrow Functions & this

const user = {
name: "Daniel",
greet: () => {
console.log(this.name);
}
};
user.greet(); // undefined

Arrow functions do not bind their own this. They inherit it from the lexical scope (i.e. the place they were defined).
If defined globally, this is the global object (or undefined in strict mode).


๐Ÿ”ธ 5. Inside Class Methods

class Person {
constructor(name) {
this.name = name;
}
sayHi() {
console.log(this.name);
}
}
const p = new Person("Daniel");
p.sayHi(); // "Daniel"

In class methods, this refers to the instance.


๐Ÿ”ธ 6. In Event Listeners

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

If you use a regular function in an event listener, this refers to the DOM element.
If you use an arrow function, this will refer to the outer context, not the element.


Want a quiz or coding challenge with tricky this examples? ๐Ÿ˜


Tags

#Javascript

Share

Related Posts

Debounce in JavaScript
Debounce in JavaScript
August 30, 2025
1 min
ยฉ 2025, All Rights Reserved.
Powered By

Social Media

githublinkedinyoutube