sequilizejs中classMethods与instanceMethods的用法



我是sequilizejs的新手,基本上是在尝试重构我在控制器中编写的代码,并遇到了classMethods和instanceMethods。我看到实例方法定义如下:

/lib/model/db/users.js

module.exports = function(sequelize, DataTypes) {
var instance_methods = get_instance_methods(sequelize);
var User = sequelize.define("User", {
email : {
type      : DataTypes.STRING,
allowNull : false
},
}, {
classMethods: class_methods,
instanceMethods : instance_methods,
});
return User;
};
function get_instance_methods(sequelize) {
return {
is_my_password : function( password ) {
return sequelize.models.User.hashify_password( password ) === this.password;
},   
};
function get_class_methods(sequelize) {
return {
hashify_password : function( password ) {
return crypto
.createHash('md5')
.update(
password + config.get('crypto_secret'),
(config.get('crypto_hash_encoding') || 'binary')
)
.digest('hex');
},
}; 

我对以上内容的理解是,classMethods是为整个模型定义的通用函数,instanceMethods基本上是对表/模型中给定行的引用,我假设这一点对吗?这将是我的首要问题。

此外,我在文档HERE中没有看到任何classMethods和instanceMethods的引用。我只在这里找到了以前的答案。这提供了对instanceMethods和classMethods之间差异的全面理解。

基本上,我只是想确认我的理解是否符合类与实例方法的预期用途,并链接到官方文档,不胜感激。

添加静态和实例方法的官方方法是使用这样的类:

class User extends Model {
static classLevelMethod() {
return 'foo';
}
instanceLevelMethod() {
return 'bar';
}
getFullname() {
return [this.firstname, this.lastname].join(' ');
}
}
User.init({
firstname: Sequelize.TEXT,
lastname: Sequelize.TEXT
}, { sequelize });

将型号视为类别

您的理解是正确的。简而言之:类可以有实例。模型就是类。因此,模型可以有实例。当使用实例方法时,您会注意到this——这是上下文,它引用了特定的类/模型实例。

因此,如果您的User型号具有:

  • 一个名为is_my_password的实例方法
  • 一个称为hashify_password的类模型

User.hashify_password('123')将返回123的哈希版本。此处不需要User实例hashify_password是附属于User模型(类(的通用函数。

现在,如果您想调用is_my_password(),则确实需要一个User实例

User.findOne({...}).then(function (user) {
if (user.is_my_password('123')) {
// ^ Here we call `is_my_password` as a method of the user instance.
...
}
}).catch(console.error)

通常,当您拥有不需要特定模型实例数据的函数时,您会将它们定义为类方法。它们是静态方法。

当函数处理实例数据时,您将其定义为实例方法,以使调用更容易、更好。

最新更新