简体   繁体   English

类方法和实例方法有什么区别[sequelize]

[英]What is the difference between class methods and instance methods [sequelize]

Sequelize allows you to add custom methods to a model , and there are two ways to do so: Sequelize允许您向模型添加自定义方法,有两种方法可以这样做:

  • classMethods: {} classMethods:{}
  • instanceMethods: {} instanceMethods:{}

In Sequelize I can't find an explanation about the differences of this two objects. 在Sequelize中,我找不到关于这两个对象之间差异的解释。 Could anyone explain the difference with an example when to use one or the other? 谁能用一个例子解释其中的区别?

Class is the object you get when you call sequelize.define . 类是调用sequelize.define时获得的对象。 It stands for the whole table. 它代表整个桌子。

var User = sequelize.define('user', {...});

Instance is like one unit of that class, ie a row in the collection's table: 实例就像该类的一个单元,即集合表中的一行:

User.create({}).then(function(user) {
  // `user` is an instance.
});

Class methods are functions that don't expect an instance. 类方法是不需要实例的函数。 You can call those like this: 您可以这样称呼:

User.myMethod();

Instance methods are ones that operate on a single instance. 实例方法是在单个实例上运行的方法。 You can call them like this: 您可以这样称呼他们:

user.myMethod();

this in class methods is a class. this类方法是一个类。 this in instance methods is an instance (obviously). this在实例方法中(显然)是一个实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM