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

前端 未结 2 963
天涯浪人
天涯浪人 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: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.

提交回复
热议问题