"这" sequelize中的关键字不是指当前实例

时间:2017-05-16 07:38:01

标签: javascript node.js sequelize.js

我创建了这样的用户模型,我想编写一个函数来更新用户的密码updatePassword():

"use strict";
var bcrypt = require('bcryptjs');

module.exports = function(sequelize, DataTypes) {
  var User = sequelize.define('User', {
    name: {
      type: DataTypes.STRING,
      allowNull: false
    },
    password: {
      type: DataTypes.STRING,
      allowNull: false
    },
    email: {
      type: DataTypes.STRING,
      primaryKey: true
    },
    phone: {
      type: DataTypes.STRING,
      allowNull: true
    }
  }, {
    instanceMethods:{
      updatePassword: function(newPass, callback){
        console.log("current pass in update: " + this.password);
        bcrypt.genSalt(10, function(err,salt){
          bcrypt.hash(newPass, salt, function(err, hashed){
            console.log("current pass: " + this.password);
            this.password = hashed;
            return callback();
          });
        });
      },
      comparePassword: function(password, callback){
        bcrypt.compare(password, this.password, function(err, isMatch){
          if(err) {
            throw err;
          }
          callback(isMatch);
        });
      }
    }

第一个日志console.log("current pass in update: " + this.password);打印当前对象的密码,但第二个console.log("current pass: " + this.password);不起作用,它会输出错误:TypeError: Cannot read property 'password' of undefined。为什么会发生以及如何解决?

1 个答案:

答案 0 :(得分:1)

这是因为您使用function来定义bycrypt

的回调

解决方案1(普通ES5)是在注册呼叫之前定义一个自我引用(想要的)this

...
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)是使用箭头功能,它会自动为您解决此问题:

...
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
    ...