我正在阅读我最近下载的库中的一些代码,以便为WebGL进行矩阵数学运算。但是,我很难围绕这个功能做什么。这来自glMatrix.js库。
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = global || self, factory(global.glMatrix = {}));
}(this, function (exports)
什么是工厂参数/功能以及出口来自哪里?有人可以一步一步地看我这个功能的作用吗?
编辑:这只是代码的第一部分,这就是开始括号永不关闭的原因。
这是一种名为UMD的设计模式,它是IIFE设计模式的更高级版本。它们都包装你的代码,创建一个新的私有范围。两者之间的主要区别在于UMD
更抽象,也可以在node.js
和amd
中工作,而不仅仅是浏览器。
你在问题中显示的第一行和最后一行基本上是IIFE
部分(减去自你裁剪后的结束)。您正在调用iife
并传递global
aka window
对象和factory
函数,您只能在代码中看到function (exports)
部分。
以下部分检查您使用的环境是node,amd还是常规JS
so,他们将在每个环境中定义模块,即node
只需要您设置exports
对象,amd
需要您使用define
函数和vanilla JS
你只需将对象添加到window
或global
对象。
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = global || self, factory(global.glMatrix = {}));
在node和amd中,您不需要为导出命名,因为您只需要该文件即const glMatrix = require("./common.js");
,但在JS中您需要从全局对象中检索,这就是为什么它只需要命名为factory(global.glMatrix = {})
。该行将glMatrix
属性添加到全局对象(最初作为空对象),然后将其作为参数传递给factory
函数,该函数附加了您应该能够从范围外访问的所有函数,值和类。
UMD
模式的实现可能因库而异。例如,这里有一种方法可以在不将任何参数传递给IIFE
的情况下完成
(function() {
var global = this;
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(global = global || self, factory(global.foo = {}));
function factory(exports) {
exports.bar = function() {
console.log("Hello World!");
};
}
})();
foo.bar();
在节点中,您只需创建一个新文件并导出您想要的任何内容。然后,Node将这些导出与文件而不是属性相关联(这是浏览器JS中发生的情况)。例如,一个名为foo.js
的文件,其中包含以下内容:
function bar() {
console.log("Hello World!");
}
exports.bar = bar;
可以从其他文件访问,如下所示:
const foo = require("foo.js");
foo.bar();
或者您可以使用Destructuring直接访问属性:
const { bar } = require("foo.js");
bar();
什么是工厂参数/功能
它是函数的第二个参数...其开头是在您包含的代码的最后一行定义的。其余的你切断了。
出口来自哪里
你打电话的时候。在这里:factory(global.glMatrix = {})