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

馋奶兔 提交于 2020-01-03 03:07:25

问题


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?


回答1:


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.




回答2:


You can see the following sample code at Why AMD

(function () {
     var $ = this.jQuery;
     this.myExample = function () {};
}());

This is an example of immediately executed factory function. So this function will execute at the time of interpretation. And we should consider loading of JQuery before this example[because it is using JQuery]. That is the job of RequireJS to load required JavaScript files as per our order.



来源:https://stackoverflow.com/questions/10013208/what-is-an-immediately-executed-factory-function-in-the-context-of-js-module-loa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!