javascript 'typeof define === 'function' && define['amd']' 用于什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30953589/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is 'typeof define === 'function' && define['amd']' used for?
提问by Suresh kumar
What purpose does the following code serve? What does factory function do here? Here root is window object. Is factory a default java script function? In what kind of scenarios this type of code can be used. This code is from toggle.js from Simon Tabor. Zepto and ender are libraries. Is this mostly used in libraries.
以下代码的用途是什么?工厂函数在这里做什么?这里 root 是窗口对象。工厂是默认的java脚本函数吗?在什么样的场景下可以使用这种类型的代码。此代码来自 Simon Tabor 的 toggle.js。Zepto 和 ender 是库。这主要用于图书馆吗?
if (typeof define === 'function' && define['amd']) {
define(['jquery'], factory);
} else {
factory(root['jQuery'] || root['Zepto'] || root['ender'] || root['$']|| $);
}
回答by Aran Mulholland
This code checks for the presence of require.js, a JavaScript dependency management library.
此代码检查是否存在require.js,这是一个 JavaScript 依赖项管理库。
If 'define' is not undefined and it is a function and 'amd' (asynchronous module definition) is also defined then the code assumes that require.js is in play.
如果 'define' 不是未定义的,并且它是一个函数并且还定义了 'amd'(异步模块定义),那么代码假定 require.js 正在起作用。
If this is so then it defines 'factory' and passes jQuery to it as a dependency. Otherwise it sets up the dependencies that the code needs by attaching them to the root object.
如果是这样,那么它定义“工厂”并将 jQuery 作为依赖项传递给它。否则,它通过将代码附加到根对象来设置代码所需的依赖项。
As for what 'factory' is: it is not defined by the Javascript framework, it will be a function in the same file most likely. It will take the parameter jQuery.
至于“工厂”是什么:它不是由 Javascript 框架定义的,它很可能是同一文件中的一个函数。它将采用参数 jQuery。