Using ES6 classes OR Object Literals in controllers for an Express + NodeJS app

前端 未结 2 965
天涯浪人
天涯浪人 2021-02-07 13:49

There are 2 things that I\'m very confused about.

  1. What is the advantage of using any of ES6 class or Object literals.

  2. And where should I use any

相关标签:
2条回答
  • 2021-02-07 14:14

    If your class has got a constructor, you can build several objects from this class threw :

    var Panier= require('./panier');    
    var panier1 = new Panier(13, 12, 25);
    var panier2 = new Panier(1, 32, 569);
    

    Of course your Panier would be defined in the file Panier.js located in the same directory :

    module.exports = class Panier
    {
        constructor(code, qte, prix)
        {
            this.codeArticle = code;
            this.qteArticle = qte;
            this.prixArticle = prix;
        }
        getCode()
        {
            return this.codeArticle;
        }
        getQte()
        {
            return this.qteArticle;
        }
        getPrix()
        {
            return this.prixArticle;
        }
    }
    
    0 讨论(0)
  • 2021-02-07 14:25

    Class Example 1: You can not create more than 1 object. Because a module is only executed once. So, on every import you will get the same object. Something similar to singleton.

    Correct. This is an antipattern therefore. Do not use it. class syntax is no replacement for object literals.

    You will not be able to access the static methods of the class because you are only exporting the object of the class.

    Theoretically you can do auth.constructor.… but that's no good.

    Class Example 2: If you have a class that contains nothing but helper methods and the object does not have any state, It makes no sense creating object of this class all the time. So, in case of helper classes, this should not be used.

    Correct. Use a simple object literal instead, or even better: multiple named exports instead of "utility objects".

    Object Literal Example: You can not do inheritance.

    You still can use Object.create to do inheritance, or parasitic inheritance, or really anything.

    Same object will be passed around on every require.

    Correct, but that's not a disadvantage. If your object contains state, you should've used a class instead.

    0 讨论(0)
提交回复
热议问题