我是sequelize.js 的新手,基本上是在尝试重构我在控制器中编写的代码并遇到了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
基本上是对表/模型中给定行的引用,我的假设正确吗?这是我的首要问题。
此外,我在文档中没有看到任何 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)
一般来说,当您拥有不需要特定模型实例数据的函数时,您会将它们定义为类方法。它们是静态方法。
当函数使用实例数据时,您可以将其定义为实例方法,以使其调用更容易、更好。