How to write JavaScript with factory functions

前端 未结 6 1312
野趣味
野趣味 2021-01-01 00:55

I\'m reading this article about perils of trying to mimic OOP in JavaScript and there\'s the following:

In JavaScript, factory functions are simply co

6条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-01 01:03

    Many answers here suggest Constructor Functions, although the name of the questions has to do with Factory Functions.

    Factory Functions look like the following:

    const RabbitFactory = () => {
      const speed = 3;
      const GetSpeed = () => speed;
      return { GetSpeed }
    }
    const rabbit = RabbitFactory();
    rabbit.GetSpeed() // -> 3
    rabbit.speed // -> undefined!
    

    I like Factory functions more than Constructor function because:

    • You don't need to get messy with prototyping
    • You don't need to use the Object constructor
    • Gives you the ability to choose what is private and what is public in your factory
      (in my example, speed is private and this is a good practice. If you want to read the value of rabbit's speed, use the GetSpeed getter)

提交回复
热议问题