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?
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
thisvalue
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With