【问题标题】:Anonymous function vs lambda in mongoose [duplicate]猫鼬中的匿名函数与lambda [重复]
【发布时间】:2016-09-09 03:15:26
【问题描述】:

我正在使用 ES6 编写 mongoose 中间件:

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

那没有用。调用了中间件,但“this”不是指正在保存的文档。然后我摆脱了 lambda 语法:

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

它成功了!

我一直很高兴在 Node 中使用 lambdas,有人知道问题出在哪里吗? (我看到这里已经有一个关于这个问题的question,不过我希望得到一个基本的答案。

【问题讨论】:

  • 一个 lambda 是一个匿名函数——一个没有名字的函数。你的两个例子都是 lambdas。但是是的,箭头函数有词法this

标签: javascript node.js mongoose ecmascript-6


【解决方案1】:

是的,这是预期的行为,当使用箭头函数时,它会捕获封闭上下文的值,这样:

function Person(){
  this.age = 0;

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

var p = new Person();

有关更多信息,请参阅下面 MDN 页面中的词汇本部分: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions#Lexical_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);
}

代码示例直接取自 MDN 文章。

【讨论】:

    猜你喜欢
    • 2012-09-27
    • 1970-01-01
    • 2020-04-25
    • 1970-01-01
    • 2011-06-23
    • 2018-12-18
    • 2023-03-14
    • 2013-08-29
    • 1970-01-01
    相关资源
    最近更新 更多