Skip to content

Odd issue with arrow functions and this scope #733

Closed

Description

@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?

Activity

  1. developit commented on Feb 9, 2015

    @developit
    Member

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

  2. chrisabrams commented on Feb 9, 2015

    @chrisabrams
    Author

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

  3. eventualbuddha commented on 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?

  4. dashed commented on Feb 9, 2015

    @dashed
    Contributor

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

    First sentence is already misleading:

    Arrows are a function shorthand using the => syntax.

  5. chrisabrams commented on Feb 9, 2015

    @chrisabrams
    Author

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

  6. sebmck commented on Feb 9, 2015

    @sebmck
    Contributor

    @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.

  7. added
    outdated
    on Jan 18, 2019
  8. locked as resolved and limited conversation to collaborators on Jan 18, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    outdated

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions