javascript - 哪些变量将被发送到匿名函数?

标签 javascript node.js

我正在使用一个名为 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)

namecontextdefinition 分别是 "reqwest"this并声明匿名函数

在浏览器中,对象 thisWindow 对象,但在 Node.js 中,它相当于 module.exports 对象(如果没有填充任何对象,则为空对象)其他模块)

现在,在匿名函数内部

(typeof module != 'undefined' && module.exports)

检查我们是否处于 Node.js 环境中,对象 modulemodule.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/

相关文章:

javascript - 如何在 Firefox 插件 sdk 扩展中使用来自 main.js 的 XMLHttpRequest。 (或类似的东西)

javascript - 在表单提交之外调用此函数

javascript - 用 python 服务器替换 Nodejs Socket.io 服务器

javascript - 将回调传递给深度嵌套函数的最佳实践

Node.js:以编程方式设置 NODE_PATH

javascript - 给对象赋值时如何调用函数

支持 Unicode 的 JavaScript pdf 生成库

javascript - 没有导出成员 'Headers' 和 RequestOptions

javascript - 为什么使用子字符串方法时应用程序挂起?

node.js - 在 Express 中, session Cookie 过期太早