Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is `this` not working in an ES6 arrow function? [duplicate]

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?

like image 992
BlackMamba Avatar asked Dec 30 '15 22:12

BlackMamba


1 Answers

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

like image 121
Barmar Avatar answered Nov 15 '22 15:11

Barmar