如何为 Sails 中的对象定义函数/实例方法?
在 Waterline 文档 ( https://github.com/balderdashy/waterline ) 中,他们说:
var User = Waterline.Collection.extend({
...
attributes: {
...
// You can also define instance methods here
fullName: function() {
return this.firstName + ' ' + this.lastName
}
},
}
但是当我尝试在 Sails 的模型中的 attributes 中定义实例方法时,该函数不会添加到对象中。 我是不是做错了什么?
环境: Sails (v0.8.94)、Node (v0.8.16)
最佳答案
您可以像这样在带有sails 0.9.0的模型中定义实例方法:
module.exports = {
attributes: {
name: {
type: 'STRING',
defaultsTo: 'zooname'
},
instanceMethod: function(){
// your code
}
}
};
使用示例:
ClientHit.findOne({}).exec(function(err, model){
model.instanceMethod(); //use your instance method
});
关于node.js - 如何使用sails.js 为模型定义实例方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17720846/