Skip to content
the poor coder

javascript this inside arrow function

Poor Man
Published
Reading time
2 min read
On this page

JavaScript this inside Arrow function#

As a JavaScript developer, you might have heard about arrow functions. They are a new way of writing functions in JavaScript that were introduced in ES6. Arrow functions are similar to regular functions but have some advantages over them. One of the advantages is that arrow functions have a lexical this binding.

When you use the this keyword inside an arrow function, it is not bound to the function itself but rather to the surrounding context. This makes arrow functions especially useful when you want to preserve the value of this from an outer scope.

Example:#

Text

let person = {
  name: "Raju",
  getFullName: function() {
    return () => {
      console.log(`My name is ${this.name}`);
    }
  }
}

let logName = person.getFullName();
logName(); // Output: My name is Raju

In the above example, we have created an object called person with a property name and a method getFullName. The getFullName method returns an arrow function that logs the person's name to the console.

Notice how we are using this.name inside the arrow function to access the person's name property. If we had used a regular function instead of an arrow function, the this keyword would have been bound to the function itself, not the person object, and we would have gotten an undefined value.

Another way of getting the same result would be to use the bind method:

Example:#

Text

let person = {
  name: "Raju",
  getFullName: function() {
    return function() {
      console.log(`My name is ${this.name}`);
    }.bind(this);
  }
}

let logName = person.getFullName();
logName(); // Output: My name is Raju

In this example, we have used the bind method to bind the value of this to the person object. This allows us to access the person's name property inside the function.

However, using an arrow function is more concise and easier to read than using the bind method. So it's always better to use arrow functions whenever possible.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC