我正在使用一个名为Reqwest的JavaScript微型库。可以执行ajax请求,但是在Internet Explorer中会引发错误。 Peer dependency xhr2 required! Please npm install 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)
检查我们是否有可用的requireJ(在浏览器环境中)。
在第一种情况下,它导出执行作为参数传递的函数的模块(这将返回对象或函数)。就像Node.js可以工作一样。
在第二种情况下,执行函数define,就像requireJs一样。
在最后一种情况下,将模块(作为函数的返回)放在上下文对象(可能是Window)中。
在函数内部,我们有:
if (context.hasOwnProperty('window')) {
这检查我们是否在浏览器环境中(“对象”窗口具有属性窗口)。
如果在浏览器中,我们有一些本机函数(例如XMLHttpRequest),但是在Node.js中,我们必须作为外部库(例如xhr2)进行加载。然后
XHR2 = require('xhr2')
等等... :)