Javascript classes vs objects, pros and cons?

后端 未结 2 465
再見小時候
再見小時候 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:36

    First of all, there are no classes in JavaScript. So what's the difference?

    • An object instantiated by a constructor has an prototype object from which it inherits properties. This prototype object is shared by all object constructed by the same function. You can put common methods on there, which will be considerably faster.
    • The constructor function is called. You can use it to initialise your object (fill in defaults, validate parameters, etc) and you have a scope to construct closures.

    Even if for some objects you don't need prototypes, a function returning plain objects for you has still advantages. At least, it provides you the flexibility to change the implementation without the need to change every instantiation in your codebase. Therefore, start with a simple

    function Car (model, miles, value, color) {
        return {model: model, miles: miles, value: value, color: color};
    }
    

    (which you can even call with new without effects) and extend it later if you need to.

提交回复
热议问题