Javascript &引用;这";sequelize中的关键字未引用当前实例
我创建了一个这样的用户模型,我想编写一个函数来更新用户的密码updatePassword():Javascript &引用;这";sequelize中的关键字未引用当前实例,javascript,node.js,sequelize.js,Javascript,Node.js,Sequelize.js,我创建了一个这样的用户模型,我想编写一个函数来更新用户的密码updatePassword(): 第一个日志console.log(“当前传入更新:+this.password”)打印当前对象的密码,但打印第二个console.log(“当前通行证:+this.password”)不起作用,它会打印一个错误:TypeError:无法读取未定义的属性“password”。为什么会发生这种情况以及如何解决?这是因为您正在使用函数定义bycrypt的回调 解决方案1(普通ES5)是在注册呼叫之前定义一个
第一个日志
console.log(“当前传入更新:+this.password”)
打印当前对象的密码,但打印第二个console.log(“当前通行证:+this.password”)代码>不起作用,它会打印一个错误:TypeError:无法读取未定义的属性“password”
。为什么会发生这种情况以及如何解决?这是因为您正在使用函数
定义bycrypt的回调
解决方案1(普通ES5)是在注册呼叫之前定义一个自我,以引用(所需)此
:
...
console.log("current pass in update: " + this.password);
var self = this;
bcrypt.genSalt(10, function(err,salt){
bcrypt.hash(newPass, salt, function(err, hashed){
console.log("current pass: " + self.password);
self.password = hashed;
...
解决方案2(Node支持了相当长一段时间的ES6)是使用一个arrow函数,它会自动为您解决这一问题:
...
console.log("current pass in update: " + this.password);
bcrypt.genSalt(10, (err,salt) => {
bcrypt.hash(newPass, salt, (err, hashed) => {
console.log("current pass: " + this.password);
this.password = hashed; // note this in an arrow function refers to the 'uppper' this
...
请在发布问题之前进行搜索,因为这之前已经被回答了很多次。对不起,我认为在Sequelize中是不同的
...
console.log("current pass in update: " + this.password);
bcrypt.genSalt(10, (err,salt) => {
bcrypt.hash(newPass, salt, (err, hashed) => {
console.log("current pass: " + this.password);
this.password = hashed; // note this in an arrow function refers to the 'uppper' this
...