0

I was writing mongoose middleware like so, using ES6:

userSchema.pre('save', (next) => {
    // something...
    next();
});

And that did not work. The middleware was invoked, but "this" did not refer to the document being saved. I then got rid of the lambda syntax:

userSchema.pre('save', function(next) {
    // something...
    next();
});

And it worked!

I've been happily using lambdas with Node for a while, does anyone know what the problem is? (I see there is a question about this issue here already, I would appreciate a fundamental answer, though).

fierval
  • 133
  • 2
  • 6
  • A lambda is an anonymous function - a function without a name. Both of your examples are lambdas. But yes, arrow functions have lexical `this`. – Mulan May 13 '16 at 04:54

1 Answers1

2

Yes, this is the expected behaviour, when using arrow functions, this captures the value of the enclosing context such that:

function Person(){
  this.age = 0;

  setInterval(() => {
    this.age++; // |this| properly refers to the person object
  }, 1000);
}

var p = new Person();

See the lexical this section in the MDN page below for more information: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions#Lexical_this

This is great because previously we'd have to write code like this:

function Person() {
  var self = this; // Some choose `that` instead of `self`. 
                   // Choose one and be consistent.
  self.age = 0;

  setInterval(function growUp() {
    // The callback refers to the `self` variable of which
    // the value is the expected object.
    self.age++;
  }, 1000);
}

The code samples are taken directly from the MDN article.

sheeldotme
  • 2,237
  • 14
  • 27