在JS模块加载的上下文中,立即执行的工厂功能是什么? [英] What is an immediately executed factory function in the context of JS module loading?

查看:132
本文介绍了在JS模块加载的上下文中,立即执行的工厂功能是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Require.js文档中的为什么使用AMD 的部分中,以下内容问:

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

今天如何定义JavaScript代码?

How are pieces of JavaScript code defined today?

其他答案如下:

  • 通过立即执行的工厂功能定义.

我了解(至少我认为是这样),javascript工厂函数只是一个返回对象新实例的函数,但是我不明白在此问题的上下文中这意味着什么.有人可以解释吗?

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?

推荐答案

我的猜测是,您不清楚JavaScript的工厂函数"与构造函数之间的区别.根据Addy Osmani的书,我通常会看到短语"立即调用的函数表达式"或IIFE. 本文,但我相信IEFF是对相同的结构.在IEFF中(使用其术语)具有以下基本公式:

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 {};})();

基本上,这是一种用于创建函数作用域的javascript模式(/hack),因此使您可以控制将该作用域中的一些但不是全部对象公开给调用者.不要将工厂函数"与构造函数混为一谈.您不会在IIFE中使用new关键字,但是会使用传统的javascript构造函数.构造函数是关于创建对象实例的,通常您将创建许多实例,每个实例具有唯一的状态.工厂函数可帮助创建干净封装的模块,通常,您只需调用一次即可获得整个应用程序生命周期中对单个模块实例的引用.

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.

这篇关于在JS模块加载的上下文中,立即执行的工厂功能是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆