Why does `this` not work in ES6 arrow function?

Here is my code:

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

But the way out: hello, undefined .

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

I think I don't understand this in arrow function? who can give me a clear explanation?

+7
javascript ecmascript-6
source share
2 answers

The arrow function retains the this binding in the closure created when the function is created. Therefore, it does not set this to the function call context.

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

From the documentation :

An arrow function expression (also called a fat arrow function) has a shorter syntax than a function expression, and lexically binds the value of this

+7
source share

The arrow function preserves the lexical area in which it was defined. Thus, this in your hello function is the same as this when the function was defined, and not the object on which this property is. This is essentially a shorthand for ES5

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

What you want is something like

 let obj = { username: 'Hans Gruber', hello() {return `hello, ${this.username}`;} }; 
+1
source share

All Articles