我希望能消除我关于箭头函数和词法 this 的一些困惑,我的 mongoose 用例。
向 mongoose Schema 添加方法时,不能使用箭头函数。根据这篇文章:https : //hackernoon.com/javascript-es6-arrow-functions-and-lexical-this-f2a3e2a5e8c4 “词法范围只是意味着它从包含箭头函数的代码中使用它。”
因此,如果我在 mongoose 方法中使用箭头函数,为什么 'this' 不指模式对象,而 pre-es6 函数呢?如果模式和箭头函数在同一个文件中,词法范围是否不绑定到模式?
谢谢!
UserSchema.methods.toJSON = function() {
const user = this;
const userObject = user.toObject();
return _.pick(userObject, ['_id', 'email']);
};
Run Code Online (Sandbox Code Playgroud)