HomeAbout Me

How `this` behaves in JavaScript

By Daniel Nguyen
Published in Javascript
April 24, 2025
1 min read

๐Ÿ”น 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

Previous Article
JavaScript interview questions

Table Of Contents

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

Related Posts

Implement this BinaryTree
April 13, 2025
1 min
ยฉ 2025, All Rights Reserved.
Powered By

Quick Links

About Me

Legal Stuff

Social Media