9

Here is my code:

'use strict';

let obj = {
  username : 'Hans Gruber',
  hello: () => 'hello, ' + this.username
};
console.log(obj.hello());

But the output is: hello, undefined.

I expect the output to be: hello, Hans Gruber.

I think I have not understood this in an arrow function. Who can give me a clear explanation?

Boann
  • 48,794
  • 16
  • 117
  • 146
BlackMamba
  • 10,054
  • 7
  • 44
  • 67

2 Answers2

11

An arrow function saves the binding of this in the closure that's created when the function is created. So it doesn't set this to the context of the call to the function.

In your case, this was bound to window when you created the object, so this.username is window.username, not obj.username.

From the documentation:

An arrow function expression (also known as fat arrow function) has a shorter syntax compared to function expressions and lexically binds the this value

Barmar
  • 741,623
  • 53
  • 500
  • 612
1

An arrow function preserves the lexical scope in which it was defined. So this in your hello function is the same as this when the function was defined, not the object on which it is a property. It is essentially shorthand for ES5's

function() {
    return 'hello, ' + this.username;
}.bind(this);

What you want is something like

let obj = {
    username: 'Hans Gruber',
    hello() {return `hello, ${this.username}`;}
};
Igor Dubinskiy
  • 373
  • 1
  • 6