I am really confused about the value of this in callbacks, well I know that the value of this is always taken from where it was called, but here in the below code, i can't figure out what's happening.
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();
}
})
});
I was watching a tutorial of node js with mongoose, so the instructor said: In the context of this callback function, the word this refers to the object, which is
let userSchema = new mongoose.Schema({
password: {
type: String,
required: true
}
});
shouldn't the user = this here refer to Node Global Object instead of that object?
so I'm really confused how this happens, for Example, if I try to mimic this code behaviour in simple 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)
})
});
this will log user as the Window Object because the callback function was called in the context of Window.
well, I know that it's a weird question to ask.