【发布时间】:2014-06-18 23:17:33
【问题描述】:
方法和静态有什么区别?
Mongoose API 将静态定义为
Statics are pretty much the same as methods but allow for defining functions that exist directly on your Model.
具体是什么意思?直接存在于模型上是什么意思?
文档中的静态代码
AnimalSchema.statics.search = function search (name, cb) {
return this.where('name', new RegExp(name, 'i')).exec(cb);
}
Animal.search('Rover', function (err) {
if (err) ...
})
【问题讨论】:
-
方法对模型的实例进行操作。静态函数仅充当辅助函数,可以执行您想要的任何操作,包括集合级别的搜索。它们不依赖于模型的实例。
-
但是方法也是在模型上定义的,并且适用于该模型的所有实例。不是吗?
-
是的,它们都是在模型上定义的。重要的是他们“采取”行动。
-
如果模型与实例绑定,那么为什么我可以使用“this”以静态方式访问模型?