How to write JavaScript with factory functions

前端 未结 6 1321
野趣味
野趣味 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:28

    Basically I would distinguish 3 approaches to create an object in JS:

    • Class
    • Constructor
    • Factory

    Here are 3 examples (considering your Rabbit's one)

    // class
    class Rabbit {
      constructor() {
        this.speed = 3; 
        // it would be so nice to have just 'static const speed = 3;' instead of
        // using constructor for that
      }
      getSpeed() {
        return this.speed;
      }
    }
    let rabbit1 = new Rabbit();
    
    // constructor
    function ConstructorRabbit(){ }
    ConstructorRabbit.prototype.speed = 3;
    ConstructorRabbit.prototype.getSpeed = function() {
      return this.speed;
    };
    let rabbit2 = new ConstructorRabbit();
    
    // factory
    const rabbitProto = {
      speed: 3,
      getSpeed() {
        return this.speed;
      }
    };
    function factoryRabbit () {
      return Object.create(rabbitProto);
    }
    let rabbit3 = factoryRabbit();
    

    I'm not sure that there are so many pros to use only factory for creating objects, but probably I can single out the one. As mentioned in the article if we refer to very famous 'Design Patterns', so we should prefer object composition instead of class inheritance. And I'm totally agree with that postulate, thus returning back to JS and ES6 classes, we can say that prototype delegation may be better than class inheritance in some cases.

    But also, we shouldn't forget this (as mentioned in the article as well) statement: "How it’s implemented doesn’t matter at all unless it’s implemented poorly". And this one, I would say, is a really good one.

提交回复
热议问题