gpt4 book ai didi

javascript - 在回调中对此感到困惑

转载 作者:搜寻专家 更新时间:2023-11-01 00:20:45 25 4
gpt4 key购买 nike

我真的很困惑 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 , callapply Function 对象的方法为 this 传递不同的值。

例如,您可以阅读 this article在 MDN 上获取详细信息。

关于javascript - 在回调中对此感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47486109/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com