Javascript classes vs objects, pros and cons?

后端 未结 2 455
再見小時候
再見小時候 2021-01-06 07:22

In my most recent javascript program (which is mostly for fun and proof-of-concept than anything else) I have a lot of different kinds of objects and of each kind I\'d have

2条回答
  •  长发绾君心
    2021-01-06 07:46

    In terms of performance, the difference comes when you add methods. If you use object literals each object needs to have a field for each method:

    obj1--> { x: 10,
              f1: method1,
              f2: method2 }
    
    obj2--> { x: 17,
              f1: method1,
              f2: method2 }
    

    With classes, you can share common properties behind a shared prototype:

    obj1--> { x:10,
              __proto__: --------> { f1: method1,
             }              /---->   f2: method2 }
                            |
    obj2--> { x:17,         |
              __proto__: ---/
            }
    

    That said, the performance differences are only going to matter if you instantiate a lot of objects and those objects have many methods and many of those methods are closures. If I were you I would give a greater emphasis to code style issues: for example, with the object literal method you can use closures to simulate private variables while if the methods are in a shared public prototype then all your instance variables need to be public.

提交回复
热议问题