javascript - 猫鼬模式。静力学不是函数
问题描述
为什么这段代码可以正常工作:
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)
解决方案
好吧,这个问题与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
推荐阅读
- karel - 如何让卡雷尔到处放蜂鸣器?
- algorithm - 找出有效的序列
- python - 运行SQL,进不去
- ios - 如何按数字顺序对一对多关系中的项目进行排序?
- javascript - 由于另一个函数,我无法执行函数
- python - 提取 Instagram 评论时,NoneType 对象不可下标
- javascript - 为什么我的按钮功能只提供一次输出?
- jmeter - jmeter中的Beanshell预处理器出现错误
- node.js - 如何将我的本地 node.js 应用程序连接到我的 Heroku Postgres 数据库?
- firebase - 如何在颤动中从 Firestore 中检索每个文档的文档 ID