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
基础教程推荐
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- 直接将值设置为滑块 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01
- Chart.js 在线性图表上拖动点 2022-01-01
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01