继承 classMethods 与 instanceMethods

Sequelize classMethods vs instanceMethods

所以开始我对 Node.js 的探索。我正在尝试学习的工具之一是 Sequelize。因此,我将开始尝试做的事情:

'use strict';
var crypto = require('crypto');

module.exports = function(sequelize, DataTypes) {
  var User = sequelize.define('User', {
    username: DataTypes.STRING,
    first_name: DataTypes.STRING,
    last_name: DataTypes.STRING,
    salt: DataTypes.STRING,
    hashed_pwd: DataTypes.STRING
  }, {
    classMethods: {

    },
    instanceMethods: {
      createSalt: function() {
        return crypto.randomBytes(128).toString('base64');
      },
      hashPassword: function(salt, pwd) {
        var hmac = crypto.createHmac('sha1', salt);

        return hmac.update(pwd).digest('hex');
      },
      authenticate: function(passwordToMatch) {
        return this.hashPassword(this.salt, passwordToMatch) === this.hashed_pwd;
      }
    }
  });
  return User;
};

我对何时使用 classMethodsinstanceMethods 感到困惑。对我来说,当我想到 createSalt()hashPassword() 应该是 class 方法时。它们是通用的,并且在大多数情况下与它们只是一般使用的特定实例没有任何关系。但是当我在 classMethods 中有 createSalt()hashPassword() 时,我无法从 instanceMethods.

调用它们

我尝试了以下变体:

this.createSalt();
this.classMethods.createSalt();
createSalt();

像下面这样的东西是行不通的,我可能只是不理解一些简单的东西。

authenticate: function(passwordToMatch) {
  console.log(this.createSalt());
  return this.hashPassword(this.salt, passwordToMatch) === this.hashed_pwd;
}

任何 hints/tips/direction 将不胜感激!

所有不修改或检查任何类型实例的方法应该是classMethod,其余的instanceMethod

例如:

// Should be a classMethods
function getMyFriends() {
  return this.find({where{...}})
}

// Should be a instanceMethods
function checkMyName() {
  return this.name === "george";
}

虽然基础知识是当您想要修改 instance 时应该使用 instance 方法(ergo 行)。我宁愿不使用不使用 class (因此 table )本身的方法污染 classMethods

在你的例子中,我会把 hashPassword 函数放在你的 class 之外,并将它作为辅助函数留在我的实用程序模块中的某个地方(或者为什么不是同一个模块,而是作为一个正常定义的函数) ...喜欢

var hashPassword = function(...) { ... }

...

...

  instanceMethods: { 
     authenticate: function( ... ) { hashPassword( ... ) }
  }

从 sequelize 3.14 开始,我发现这对我有用

var myModel = sequelize.define('model', {

}, {
  classMethods: {
    someClassMethod: function() {
      return true;
    }
}, {
  instanceMethods: {
    callClassMethod: function() {
      myModel.someClassMethod();
    }
  }
});