Understanding “this” in JavaScript
Michael Mitrakos
4 min read
Having worked across sites raking in over 50 billion website visits annually with Higglo Digital I write about tech topics and teach engineers to have solid foundations that will help them get ahead in their career. I also build awesome products for digital nomads — check it out!
JavaScript eBook
I’ve written an eBook on JavaScript that will take you from beginner to professional. Having been in your shoes moving to making over $200,000 per year in just a few years as a software engineer, I know exactly what it takes to get there. Check out the ebook now!
In JavaScript, the this keyword refers to the object that is currently executing the code. It can be used to refer to the object itself, or to access its properties and methods.
One common use of this is to refer to the current object inside a method. For example:
const obj = {
name: 'My Object',
sayName: function() {
console.log(`My name is ${this.name}`);
}
}
obj.sayName(); // Output: "My name is My Object"In this example, the sayName method uses this to access the name property of the obj object.
Another common use of this is to bind a function to a specific object. This can be useful when passing a method as a callback, or when working with event handlers.
For example:
const button = document.querySelector('button');
const obj = {
name: 'My Object',
sayName: function() {
console.log(`My name is ${this.name}`);
}
}
button.addEventListener('click', obj.sayName.bind(obj));In this example, the sayName method is bound to the obj object using the bind method. When the button is clicked, the sayName method will be executed with this set to the obj object, rather than the button element.
It’s important to note that the value of this can change depending on how a function is called. In the examples above, this refers to the object that the function is a property of. However, if the function is called as a standalone function, this will refer to the global object (usually window in the browser).
For example:
function sayName() {
console.log(`My name is ${this.name}`);
}
const obj = {
name: 'My Object',
sayName: sayName
}
obj.sayName(); // Output: "My name is My Object"
sayName(); // Output: "My name is undefined" (in the browser)In the second example, the sayName function is called directly, so this refers to the global object. To avoid this behavior, you can use the bind method, as shown in the previous example, or you can use the call or apply methods to specify the value of this when calling the function.
For example:
function sayName(greeting) {
console.log(`${greeting} My name is ${this.name}`);
}
const obj = {
name: 'My Object'
}
sayName.call(obj, 'Hello'); // Output: "Hello My name is My Object"
sayName.apply(obj, ['Hello']); // Output: "Hello My name is My Object"In these examples, the call and apply methods are used to specify the value of this when calling the sayName function. The first argument to call or apply is the value of this that you want to use, and any additional arguments are passed to the function as normal.
JavaScript eBook
I’ve written an eBook on JavaScript that will take you from beginner to professional. Having been in your shoes moving to making over $200,000 per year in just a few years as a software engineer, I know exactly what it takes to get there. Check out the ebook now!
I founded Higglo Digital and we can help your business crush the web game with an award-winning website and cutting-edge digital strategy. If you want to see a beautifully designed website, check us out.
I also created Wanderlust Extension to discover the most beautiful places across the world with highly curated content. Check it out!
Related reading
Master Recursion in JavaScript: Tips, Tricks, and Examples
Diving into the world of JavaScript, we often encounter concepts that seem daunting at first glance. Recursion is one such concept, a powerful tool that, when…
JavaScript Promises Explained for Beginners: Master Async Code
If you’ve ever found yourself scratching your head over asynchronous operations in JavaScript, you’re not alone. It’s a common hurdle for beginners, but that’s…
Beginner’s Guide to JavaScript Cross-Browser Compatibility
Ever found yourself scratching your head wondering why your JavaScript code works like a charm in Chrome but throws a tantrum in Internet Explorer? Welcome to…