Amit Dimri
Amit Dimri

Reputation: 691

How to bind 'this' to an object arrow function?

Let us suppose we have an object profile with properties name and getName method (arrow function).

profile = {
    name: 'abcd',
    getName: () => {
        console.log(this.name);
    }
}

I want to call getName method by keeping the arrow function intact, and not changing it to regular function.

How can I get the output abcd by calling getName().

You can add expressions inside getName.

Will call() or bind() help? If so, how?

DO NOT CHANGE THE ARROW FUNCTION TO REGULAR FUNCTION

-- EDITED --

I just want to ask how can we use arrow functions inside objects so that it reflect the results as we will get in regular functions.

It was just an interview question.

Upvotes: 0

Views: 323

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370689

Without changing it to a regular function, the only way to get to the name property from the inner function is through accessing the outer variable name, which is profile:

const profile = {
    name: 'abcd',
    getName: () => {
        console.log(profile.name);
    }
}

profile.getName();

Upvotes: 8

Related Questions