Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 490
user1532043 Avatar asked Jul 26 '16 11:07

user1532043


1 Answers

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

like image 97
Anirudh Modi Avatar answered Nov 16 '22 00:11

Anirudh Modi