Sequelize classMethods vs instanceMethods(续集 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";
}
这篇关于续集 classMethods 与 instanceMethods的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:续集 classMethods 与 instanceMethods


基础教程推荐
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01