续集 classMethods 与 instanceMethods [英] Sequelize classMethods vs instanceMethods

查看:11
本文介绍了续集 classMethods 与 instanceMethods的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以开始我对 Node.js 的所有事物的冒险.我正在尝试学习的工具之一是 Sequelize.所以我将开始我想做的事情:

So starting my adventure into all things Node. One of the tools I am trying to learn is Sequelize. So I will start off what I was trying to do:

'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() 应该是类方法.它们是通用的,并且在大多数情况下与它们通常使用的特定实例没有任何关系.但是当我在 classMethods 中有 createSalt()hashPassword() 时,我无法从 instanceMethods 调用它们.

I am confused on when to use classMethods vs instanceMethods. To me when I think about createSalt() and hashPassword() should be class methods. They are general and for the most part dont really have anything to do with the specific instance they are just used in general. But when I have createSalt() and hashPassword() in classMethods I cannot call them from instanceMethods.

我尝试了以下变体:

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

像下面这样的东西不起作用,我可能只是不理解一些简单的东西.

Something like below wont work and I am probably just not understanding something simple.

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

非常感谢任何提示/提示/方向!

Any hints/tips/direction would be very much so appreciated!

推荐答案

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

All the method who don't modify or check any type of instance should be classMethod and the rest instanceMethod

例如:

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

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

这篇关于续集 classMethods 与 instanceMethods的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆