在初始化期间设置 Bookshelf 属性会引发 'this' 未定义的错误

Setting Bookshelf attribute during initialization throws an error on 'this' being undefined

我在 Bookshelf 模型中看到关于 'this' 的奇怪行为,我很困惑。我正在尝试使用 'saving' 事件上的挂钩来散列密码。但是,如果我尝试 get/set 'this' 上的属性,它会抱怨 'this' 未定义:

'use strict';

var DB = require('../config/db'),
    _ = require('underscore'),
    str = require('underscore.string'),
    Base = require('./base'),
    Promise = require('bluebird'),
    bcrypt = Promise.promisifyAll(require('bcrypt'));

var User = DB.Model.extend({
  tableName: 'users',
  hasTimestamps: ['createdAt', 'updatedAt'],

   // convert snake_case to camelCase
  parse: function(attrs) {
    return _.reduce(attrs, function(memo, val, key) {
      memo[str.camelize(key)] = val;
      return memo;
    }, {});
  },

  // convert camelCase to snake_case
  format: function(attrs) {
    return _.reduce(attrs, function(memo, val, key) {
      memo[str.underscored(key)] = val;
      return memo;
    }, {})
  },

  initialize: function() {
    this.on('saving', this.hashPassword, this);
  },

  hashPassword: function() {
    return bcrypt.genSaltAsync(10).then(function(salt){
      return bcrypt.hashAsync(this.get('password'), salt);
    }).then(function(hash){
      this.set({'password':hash});
    });
  }
});

module.exports = User;

当我尝试保存用户模型时,我看到了以下堆栈跟踪:

Debug: internal, implementation, error 
    Error: TypeError: Cannot call method 'get' of undefined
    at Object.exports.create (/usr/src/app/node_modules/boom/lib/index.js:21:17)
    at Object.exports.internal (/usr/src/app/node_modules/boom/lib/index.js:254:92)
    at Object.exports.badImplementation (/usr/src/app/node_modules/boom/lib/index.js:290:23)
    at null.<anonymous> (/usr/src/app/routes/users.js:31:20)
    at tryCatcher (/usr/src/app/node_modules/bluebird/js/main/util.js:24:31)
    at Promise._settlePromiseFromHandler (/usr/src/app/node_modules/bluebird/js/main/promise.js:454:31)
    at Promise._settlePromiseAt (/usr/src/app/node_modules/bluebird/js/main/promise.js:530:18)
    at Promise._settlePromises (/usr/src/app/node_modules/bluebird/js/main/promise.js:646:14)
    at Async._drainQueue (/usr/src/app/node_modules/bluebird/js/main/async.js:177:16)
    at Async._drainQueues (/usr/src/app/node_modules/bluebird/js/main/async.js:187:10)
    at Async.drainQueues (/usr/src/app/node_modules/bluebird/js/main/async.js:15:14)
    at process._tickDomainCallback (node.js:486:13)

有什么想法吗?

这个有用吗?

hashPassword: function() {

    var self = this;

    return bcrypt.genSaltAsync(10).then(function(salt) {
        return bcrypt.hashAsync(self.get('password'), salt);
    }).then(function(hash) {

        self.set({
            'password': hash
        });

    });
}