Constructor function vs Factory functions

后端 未结 7 956
清酒与你
清酒与你 2020-11-22 06:52

Can someone clarify the difference between a constructor function and a factory function in Javascript.

When to use one instead of the other?

7条回答
  •  轮回少年
    2020-11-22 07:14

    Factories are a layer of abstraction, and like all abstractions they have a.cost in complexity. When encountering a factory based API figuring out what the factory is for a given API can be challenging for the API consumer. With constructors discoverability is trivial.

    When deciding between ctors and factories you need to decide if the complexity is justified by the benefit.

    Worth noting that Javascript constructors can be arbitrary factories by returning something other than this or undefined. So in js you can get the best of both worlds - discoverable API and object pooling/caching.

提交回复
热议问题