我正在编写像这样的mongoose中间件,使用ES6:
userSchema.pre('save', (next) => {
// something...
next();
});
这不起作用。中间件被调用,但“this”没有引用正在保存的文档。然后我摆脱了lambda语法:
userSchema.pre('save', function(next) {
// something...
next();
});
它有效!
我一直很高兴地使用Lambdas和Node一段时间,有谁知道问题是什么? (我已经看到这里有一个关于这个问题的question,我会很感激一个基本的答案。
答案 0 :(得分:2)
是的,这是预期的行为,当使用箭头函数时,它会捕获封闭上下文的值,以便:
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文章。