首页 > 解决方案 > 猫鼬模式。静力学不是函数

问题描述

为什么这段代码可以正常工作:

schema.statics.findByName = function (name) {
  return this.findOne({ username: name });
};

但是当我尝试这个时

schema.statics.findByName =  (name) => {
  return this.findOne({ username: name });
};

打电话时TypeError: this.findOne is not a function出错User.findByName(username)

标签: javascriptnode.jsmongoose

解决方案


好吧,这个问题与mongoDB和mongoose无关。为此,首先我们需要了解 JavaScript 中普通函数和箭头函数的区别。

与常规函数相比,箭头函数对“this”的处理是不同的。简而言之,箭头函数没有 this 的绑定。

在常规函数中,this 关键字表示调用函数的对象,可以是窗口、文档、按钮或其他任何东西。

对于箭头函数,this 关键字始终表示定义箭头函数的对象。他们没有自己的这个。

let user = { 
name: "Stackoverflow", 
myArrowFunc:() => { 
    console.log("hello " + this.name); // no 'this' binding here
}, 
myNormalFunc(){        
    console.log("Welcome to " + this.name); // 'this' binding works here
}
};

user.myArrowFunc(); // Hello undefined
user.myNormalFunc(); // Welcome to Stackoverflow

推荐阅读