Search code examples
javascriptrequirejs-amd

What is an immediately executed factory function in the context of JS module loading?


In the Require.js documentation, in the section called Why AMD, the following is asked:

How are pieces of JavaScript code defined today?

Among other answers is the following:

  • Defined via an immediately executed factory function.

I understand (at least I think I do) that a javascript factory function is simply a function that returns a new instance of an object, but I don't understand what this means in the context of this question. Can someone explain this?


Solution

  • My guess is you are not clear about the different between a javascript "factory function" and a constructor function. I usually see the phrase "immediately-invoked function expression" or IIFE as per Addy Osmani's book or this article, but I believe IEFF is a reference to the same structure. In IEFF (using their terminology) has this basic formula:

    (function () { return {};})();
    

    It's basically a javascript pattern (/hack) used to create a function scope and thus give you control over exposing some but not all of the objects within that scope to the caller. Don't get "factory function" confused with a constructor function. You don't use the new keyword with an IIFE, but you do with a traditional javascript constructor function. Constructor functions are about creating object instances and typically you will create many instances, each with unique state. Factory functions help create cleanly encapsulated modules and typically you only need to invoke it once and get a reference to a single module instance for you entire application lifetime.