Why “this” is undefined inside a fat arrow function definition? [duplicate]

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


The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .
Read More:   Jquery Datatables column rendering and sorting

Similar Posts