17

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.

user1532043
  • 709
  • 2
  • 12
  • 23
  • Yes, this question does answer it: http://stackoverflow.com/questions/31095710/methods-in-es6-objects-using-arrow-functions – Ashwin Ramaswami Jul 26 '16 at 11:59
  • https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions – Dellirium Jul 26 '16 at 12:02
  • Also a duplicate of [Arrow function vs function declaration / expressions: Are they equivalent / exchangeable?](http://stackoverflow.com/q/34361379/218196) – Felix Kling Jul 26 '16 at 19:43

1 Answers1

19

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

ramiwi
  • 486
  • 2
  • 6
  • 22
Anirudh Modi
  • 1,530
  • 9
  • 8
  • 3
    `obj.foo();` will print `undefined`,not `global!!!`. – Suvitruf - Andrei Apanasik Aug 20 '18 at 11:56
  • yes because "global!!!" is printed in the console statement – Shubham1164 Oct 08 '19 at 05:47
  • I would like to add that since `let` does not create a property on the global object, if `a` in the first example was declared like `let a = 'global!!!'`. Then the result will be `undefined`. – Rain Oct 29 '20 at 09:12
  • @Suvitruf-AndreiApanasik Are you sure you run the code in the browser or in the command line with `Node.js`? . `Node.js` has no window object, maybe that's why the result was `undefined`. Or maybe `a` was declared with `let` which I explained why in the other comment. – Rain Oct 29 '20 at 09:17