First I tried this -
const profile = {
name: 'Alex',
getName: function(){
return this.name;
}
};
Which works fine. Now I tried the same thing with fat arrow. In that case "this" is coming undefined.
const profile = {
name: 'Alex',
getName: () => {
return this.name;
}
};
This gives me an error
TypeError: Cannot read property 'name' of undefined
What I learned was, fat arrow syntaxes are way better handling implicit "this". Please explain why is this happening.
Unlike regular functions, Arrow functions does not have a this
of their own, only regular functions and global scope have this
of their own.
Which would mean that whenever this
would be referred in arrow function, it will start looking up the scope to find the value of this
, or in this case, during lookup it found, that the object
is not having a this
of its own, hence, it went up to global scope and bound the value of this
with global scope, where it won't find anything. These two examples will solve your doubt.
var obj = {
a : 'object???',
foo : () => { console.log(this.a) }
};
var a = 'global!!!';
obj.foo(); // global!!!
Wrapping arrow within a function
var obj = {
a : 'object???',
foo : function() {
return (() => {
console.log(this.a)
})();
}
};
var a = 'global!!!';
obj.foo();
Here, I have tried to explain the behaviour of this
for arrow in depth.
https://github.com/anirudh-modi/JS-essentials/blob/master/ES2015/Functions/Arrow%20functions.md#how-this-is-different-for-arrow-functions
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