var obj = {
name: 'hello',
getName: function(){
return () => {return this.name; }
}
}
var name = 'world';
var nameFunc = obj.getName();
console.log(nameFunc())
And the result is "hello",not "world". I am a little confused.
var obj = {
name: 'hello',
getName: function(){
return () => {return this.name; }
}
}
var name = 'world';
var nameFunc = obj.getName();
console.log(nameFunc())
And the result is "hello",not "world". I am a little confused.
Arrow functions are "born" bound to the value of this
as it was at the time of their creation. When you make your call to getName()
:
var nameFunc = obj.getName();
then inside getName()
the value of this
is a reference to obj
. Your return
statement constructs the arrow function, and that function is therefore bound to obj
. It's as if you'd written:
getName: function() {
return function() {
return this.name;
}.bind(this);
}
That's just the way arrow functions work, and yes it's different from regular functions.