javascript - "this"sequelize中的关键字不引用当前实例

标签 javascript node.js sequelize.js

这个问题在这里已经有了答案:





Javascript "this" scope

(3 个回答)


4年前关闭。




我创建了一个这样的用户模型,我想编写一个函数来更新用户的密码 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 .为什么会发生以及如何解决?

最佳答案

这是因为您使用的是 functionbycrypt 定义回调

解决方案 1(普通 ES5)是定义一个 self 来引用(想要的)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
    ...

关于javascript - "this"sequelize中的关键字不引用当前实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43995215/

相关文章:

sequelize.js - Sequelize 查询 - 比较两列中的日期

javascript - 将 javascript 添加到 drupal 无法识别某些 jquery

javascript 链接分页

javascript - 如何获得 Mongoose 属性(property)的总和?

javascript - 如何在elasticsearch客户端搜索功能中仅获取 '_source'字段?

javascript - 尝试通过获取请求发送一个值,获取该值但它不发送 html 页面作为响应

javascript - 在 angularjs 应用程序的主页上使用 fullPage.js,必须在路线更改时销毁

javascript - 为什么我在尝试使用 vanilla JS 将数据发布到 API 时收到 422(无法处理的实体)错误?

node.js - 如何使用 node.js aws-sdk、cloudwatch 和 lambda 函数安排调用 API

sequelize.js - Sequelize : Why am i getting Unhandled rejection SequelizeDatabaseError: column Receiver. 接收器不存在