续集 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;
};
我对何时使用 classMethods
和 instanceMethods
感到困惑.对我来说,当我想到 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";
}
相关文章