Odd issue with arrow functions and this scope #733

Closed
chrisabrams opened this Issue Feb 9, 2015 · 8 comments

Projects

None yet

7 participants

@chrisabrams

When using the npm library thinky, I have the following snippet of code:

User.pre('save', (next) => {

    console.log("pre save event\n", this)
    next()

})

Where this will be undefined. However, if I change the arrow function to an ES5 function:

User.pre('save', function(next) {

    console.log("pre save event\n", this)
    next()

})

this is defined as expected. What would cause this to be undefined with an arrow function?

@chrisabrams chrisabrams referenced this issue in neumino/thinky Feb 9, 2015
Closed

`this` in `pre('save')` is undefined. #177

@developit

this is lexically scoped in arrow functions. See #730.

@chrisabrams

Ah ok...learned something new today :) Thanks @developit and @stebru

@chrisabrams chrisabrams closed this Feb 9, 2015
@eventualbuddha
Member

@sebmck, this is the third or fourth example of this sort of question being raised. Do you think we should put it on the website or docs somewhere?

@dashed
Contributor
dashed commented Feb 9, 2015

Yes please.
https://6to5.org/docs/learn-es6/#arrows

First sentence is already misleading:

Arrows are a function shorthand using the => syntax.

@chrisabrams

That is exactly how I was mislead. I did not realize that the => behaves similarly to the => in CoffeeScript.

@thejameskyle
Member

Open an issue in https://github.com/6to5/6to5.github.io please

@kittens
Member
kittens commented Feb 9, 2015

@eventualbuddha Not sure if there's anything else that can be done since in all the examples where arrow functions are shown they're always presented with an automatic lexical scope binding.

@kittens kittens added the invalid label Feb 9, 2015
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment