0

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.

Amit Dimri
  • 681
  • 5
  • 6
  • *Will call() or bind() help?* Arrow functions do not have context to override, so you cannot use `.bind` or `.call` – Rajesh Aug 31 '18 at 10:04
  • as a side note : javascript has [`getters`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get) – jonatjano Aug 31 '18 at 10:05
  • `this` inside arrow functions is *explicitly literal*. That's one of their distinguishing features. It's explicitly impossible to change their `this` binding. – deceze Aug 31 '18 at 10:05
  • 1
    Possible duplicate of [Self-references in object literal declarations](https://stackoverflow.com/questions/4616202/self-references-in-object-literal-declarations) – Rajesh Aug 31 '18 at 10:06
  • 3
    Why are you so adamant about using an arrow function when it's exactly the thing causing a problem? – deceze Aug 31 '18 at 10:10
  • 1
    @deceze this is not for use, it was asked by an interviewer. – Amit Dimri Aug 31 '18 at 10:18

1 Answers1

8

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();
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • I guess we should close it as dupe. Though not exact dupe, linked post surely solves the problem. – Rajesh Aug 31 '18 at 10:09
  • 3
    @Rajesh That "dupe" is rather different. – deceze Aug 31 '18 at 10:11
  • @deceze OP is focused on using arrow function but inherently, what we are trying to achieve is to have a self reference in a method. Following [answer](https://stackoverflow.com/a/14206385/3783478) has very similar approach. Hence, I marked it as dupe. If i have misunderstood the question, apologies! – Rajesh Aug 31 '18 at 10:14