我正在使用一个名为 Reqwest 的 javascript 迷你库。它应该执行 ajax 请求,但在 Internet Explorer 中它会抛出错误。 需要对等依赖 xhr2!请 npm 安装 xhr2'
。 Xhr2 是一个应该与 node.js 一起使用的库,我在前端运行代码。
我试图理解这段代码的作用、它是如何执行的以及变量来自哪里。我现在最好的选择是,由于某种原因 context.hasOwnProperty('window')
为 false,并且假设代码正在服务器端运行。但我不知道为什么。
!function (name, context, definition) {
if (typeof module != 'undefined' && module.exports) module.exports = definition()
else if (typeof define == 'function' && define.amd) define(definition)
else context[name] = definition()
}('reqwest', this, function () {
var context = this
if (context.hasOwnProperty('window')) {
var doc = document
, byTag = 'getElementsByTagName'
, head = doc[byTag]('head')[0]
} else {
var XHR2
try {
XHR2 = require('xhr2')
} catch (ex) {
throw new Error('Peer dependency `xhr2` required! Please npm install xhr2')
}
}
...
}
最佳答案
首先。
!function(){}();
这是
的快捷方式( function() {} )();
只需立即执行匿名函数function() {}
例如,
!function(arg1){ console.log(arg1); }("argument1");
将打印argument1
。
现在:
!function(name,context, definition)
name
、context
和 definition
分别是 "reqwest"
、this
并声明匿名函数
在浏览器中,对象 this
是 Window
对象,但在 Node.js 中,它相当于 module.exports 对象(如果没有填充任何对象,则为空对象)其他模块)
现在,在匿名函数内部
(typeof module != 'undefined' && module.exports)
检查我们是否处于 Node.js 环境中,对象 module
和 module.exports
是否始终已定义。
(typeof define == 'function' && define.amd)
检查我们是否有可用的 requireJs(在浏览器环境中)。
在第一种情况下,它导出执行作为参数传递的函数的模块(将返回一个对象或函数)。就像 Node.js 的工作原理一样。
在第二种情况下执行函数定义,就像 requireJs 一样。
在最后一种情况下,将模块(作为函数的返回)放入上下文对象(可能是 Window)中。
在函数内部我们有这个:
if (context.hasOwnProperty('window')) {
这检查我们是否在浏览器环境中(对象窗口具有属性窗口)。 如果我们在浏览器中,我们有一些 native 函数(如 XMLHttpRequest),但在 Node.js 中我们必须作为外部库加载(如 xhr2)。然后
XHR2 = require('xhr2')
等等...:)
关于javascript - 哪些变量将被发送到匿名函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31559561/