lundi 17 décembre 2018

What design pattern is this code adhering to?

Upon exploring a JavaScript library I was interested in, I came across this strange IIFE. I cannot find any information on this pattern and am lead to believe its custom tailored for this use case. I can't quite wrap my head around what is happening here, but intuition has me thinking it may be similar to the Singleton pattern. Here is a shortened example showing off what I believe to be the core of the code:

var Ctor = (function () {

  function dostuff(_this, args...){}//only used within this iife

  var Ctor = function (args...) {
    if (!this || this === window) {
      return new Ctor(args...);
    }
    dostuff(this, args...);
    return this;
  };
  return Ctor;
})();

Note, I changed the names of the functions to reflect what I believe they're responsible for, but my assumptions could be wrong and I could be further making the code unintelligible. The source I linked to is about 60 lines long so I'd suggest giving that a look for hints if this version makes no sense. (Changes I made are Ctor <=> Bind, dostuff <=> extend)

As for my questions:

  1. What is this design pattern? (if applicable)
  2. What is the inspiration for using a pattern like this?
  3. What are some other real world applications for this pattern?
  4. Is there a more standard/readable way of writing this that produces the same functionality?

Aucun commentaire:

Enregistrer un commentaire