Sequelize classMethods vs instanceMethods

后端 未结 3 1562
盖世英雄少女心
盖世英雄少女心 2021-02-12 23:48

So starting my adventure into all things Node. One of the tools I am trying to learn is Sequelize. So I will start off what I was trying to do:



        
相关标签:
3条回答
  • 2021-02-13 00:02

    All the method who don't modify or check any type of instance should be classMethod and the rest instanceMethod

    ex:

    // Should be a classMethods
    function getMyFriends() {
      return this.find({where{...}})
    }
    
    // Should be a instanceMethods
    function checkMyName() {
      return this.name === "george";
    }
    
    0 讨论(0)
  • 2021-02-13 00:17

    I found this worked for me as of sequelize 3.14

    var myModel = sequelize.define('model', {
    
    }, {
      classMethods: {
        someClassMethod: function() {
          return true;
        }
    }, {
      instanceMethods: {
        callClassMethod: function() {
          myModel.someClassMethod();
        }
      }
    });
    
    0 讨论(0)
  • 2021-02-13 00:19

    Although the basics are that instance methods should be used when you want to modify your instance ( ergo row ). I would rather not pollute the classMethods with methods that don't use the class ( ergo the table ) itself.

    In your example I would put hashPassword function outside your class and leave it as a helper function somewhere in my utilities module ( or why not the same module but as a normal defined function ) ... like

    var hashPassword = function(...) { ... }
    
    ...
    
    ...
    
      instanceMethods: { 
         authenticate: function( ... ) { hashPassword( ... ) }
      }
    
    0 讨论(0)
提交回复
热议问题