0
var test = {
    literalLogger: function() {
        console.log('literal')
        console.log('this: ', this)
    },
    arrowLogger: () => {
        console.log()
        console.log('this: ', this)
    },
    nestedArrowLogger() {
        this.arrowLogger();
    }
}

The first function logs this as the object. The second function logs this as the window. The third function logs this as the window.Why?

  • 1
    All your functions belong to an object called 'test'.. So in your first example, it indeed will return the `test` object. Arrow functions capture the scope, iow: they don't change your this to point at `test`, but the context that was before it, in this case `window`,.. Your third example is just really repeating the 2nd. – Keith Aug 23 '17 at 01:02
  • 1
    @Keith That is not quite right. The functions are certainly attached to the `test` object, but that is no guarantee that `this` in the function will be `test`. That entirely depends on how the individual functions are _called_. Also did you typo your last comment? The third is similar to the first, not the second. – loganfsmyth Aug 23 '17 at 01:06
  • 1
    Why was this downvoted? Seems like a valid question. Also hi @loganfsmyth – djfdev Aug 23 '17 at 01:09
  • See [MDN Arrow Functions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions). "...does not bind its own `this`" – styfle Aug 23 '17 at 01:19
  • 1
    @loganfsmyth Indeed, it depends on how the functions are called.. In this example I'm assuming they are called from test.*. eg. test.literalLogger(), of course bind & call can change things. I meant 3rd same as 2nd, if calling from test.*, as 2nd has already got it's context scoped. – Keith Aug 23 '17 at 01:23
  • @Keith Gotcha, always good to clarify since they could just as easily do `var logger = tests.literalLogger; logger();` or something. Also, maybe I misunderstood what your statement about 2/3 was. My point was that the `this` inside the third is resolved the same way it is in the first case, where I thought you were saying it is resolved like an arrow function, but you are right that since it calls the arrow function the final behavior is like you called the second directly. – loganfsmyth Aug 23 '17 at 01:32

1 Answers1

3

Fat arrow functions capture the this keyword relatively to what it is in the context they are declared in (for the second one this is the window).

As for the third one, it might be because x() in an object literal is a shorthand for x: function()?

Vivick
  • 2,051
  • 2
  • 6
  • 19