Sitemap

this in JavaScript

2 min readDec 19, 2024

--

In JavaScript, the this keyword is a powerful but often confusing concept. Its value depends on the execution context and basically refers to the “owner” of the executing function or method. Let’s break down how this works in different contexts:

1. this in the Global Context

In the global execution context, this refers to the global object. In a browser environment, this is the window object; in Node.js, it’s the global object.

console.log(this); // In browsers, this logs the window object

2. this Inside a Function

In a regular function, the value of this defaults to the global object. However, in strict mode ('use strict'), this will be undefined.

function showContext() {
console.log(this); // window or global object
}

function showStrictContext() {
'use strict';
console.log(this); // undefined
}

showContext();
showStrictContext();

3. this in Object Methods

When a function is called as a method of an object, this refers to the object that owns the method.

const car = {
brand: 'Tesla',
getBrand: function() {
console.log(this.brand);
}
};

car.getBrand(); // 'Tesla'

4. this in Constructor Functions

In constructor functions, this refers to the newly created object.

function Vehicle(model) {
this.model = model;
}

const vehicle = new Vehicle('BMW');
console.log(vehicle.model); // 'BMW'

Get eunbi’s stories in your inbox

Join Medium for free to get updates from this writer.

5. this in Event Handlers

In event handlers, this refers to the element that received the event.

document.getElementById('myBtn').addEventListener('click', function() {
console.log(this); // The button element with the ID 'myBtn'
});

6. this in Arrow Functions

Arrow functions differ from regular functions in that they don’t have their own this. Instead, they inherit this from the enclosing execution context at the time of their creation.

const smartphone = {
brand: 'Apple',
regularFunction: function() {
setTimeout(function() {
console.log(this.brand); // undefined (refers to global object in non-strict mode)
}, 100);
},
arrowFunction: function() {
setTimeout(() => {
console.log(this.brand); // 'Apple'
}, 100);
}
};

car.regularFunction();
car.arrowFunction();

In the example above:

  • regularFunction’s setTimeout callback is a regular function and thus has its this bound to the global object.

arrowFunction’s setTimeout callback is an arrow function, so it inherits this from the enclosing arrowFunction context, which is the smartphone object.

Conclusion

Understanding this in JavaScript is essential for writing effective and bug-free code. By knowing how this behaves in different contexts—global, function, object methods, constructors, event handlers, and arrow functions—you can leverage its power to build dynamic and flexible applications.

--

--