- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我真的很困惑 this 在回调中的值(value),我知道 this 的值(value)总是从它被调用的地方获取,但在下面的代码中,我无法弄清楚发生了什么。
userSchema.pre("save", function(next) {
let user = this;
bcrypt.hash(user.password, 10, function(err, hash) {
if (err) {
next(err)
} else {
user.password = hash;
next();
}
})
});
我在看一个node js和mongoose的教程,所以导师说:在此回调函数的上下文中,单词this 指的是对象,即
let userSchema = new mongoose.Schema({
password: {
type: String,
required: true
}
});
这里的 user = this
不应该指的是 Node 全局对象而不是那个对象吗?
所以我真的很困惑这是怎么发生的,例如,如果我尝试在简单的 JavaScript 中模仿这种代码行为。
function UserSchema() {
this.pre = function(cb) {
return cb();
}
}
function Bycrypt() {
this.hash = function(cb) {
return cb();
}
}
userSchema.pre(function() {
var user = this;
bycrypt.hash(function() {
console.log(user)
})
});
这会将用户记录为 Window 对象,因为回调函数是在 Window 的上下文中调用的。
好吧,我知道这个问题很奇怪。
最佳答案
this
在 JavaScript 函数中指的是执行上下文,在正常情况下(不是 ES6 特定的“箭头”函数)通常等于上下文,函数被调用。但是“this”可以是由例如更改使用 bind , call或 apply Function 对象的方法为 this
传递不同的值。
例如,您可以阅读 this article在 MDN 上获取详细信息。
关于javascript - 在回调中对此感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47486109/
我正在尝试学习Rust。我正在阅读一本书online,该书实现了unix程序cat。现在,我试图读取作为像cargo run file1.txt file2.txt这样的参数传递的文件的内容,但是程序
我在 GHC 8.0.1 中遇到了一个带有种类索引 (?) GADT 的奇怪情况,其中在类型与种类签名中引入 foralls 会产生不同的类型检查行为。 考虑以下数据类型: {-# LANGUAGE
我正在使用 Perl 5.10 开发应用程序,HTML::Mason和 Apache 2.2。这是我第一次在大型项目中使用 Perl 5.10。我每隔一段时间就会出现奇怪的行为。应用程序因一个非常奇怪
我正在尝试将文件上传到aws中的rust中,因为我使用的是 rusoto_s3 的s3 rust客户端,当这些部分从单个线程发送时,我设法使分段上传代码正常工作不是我想要的,我想上传大文件,并且希望能
我是一名优秀的程序员,十分优秀!