javascript - 在 Node js 控制台和浏览器之间的箭头函数中使用参数时的不同输出

标签 javascript node.js browser arguments arrow-functions

文档在这里 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#No_binding_of_arguments 说箭头函数没有自己的参数对象。 所以当我们在箭头函数中使用它时,它应该是未定义的。 但是我在 nodejs consolebrowser(Firefox Developer 70.0b2) 之间得到了不同的结果。

我在网上搜索过,但找不到官方文档。

let arrowFun = () => {
  console.log(arguments);
};

arrowFun("a", "b", "c");
  1. 在 Nodejs 控制台中,我希望输出是未定义的,但实际输出是:
[Arguments] {
      '0': {},
      '1':
       { [Function: require]
         resolve: { [Function: resolve] paths: [Function: paths] },
         main:
          Module {
            id: '.',
            exports: {},
            parent: null,
            filename: 'e:\\workspace\\firefox-webide-test\\test\\app.js',
      ... omitted for brevity ...
}
  1. 在浏览器中,我得到了正确的输出:undefined

最佳答案

那是因为NodeJS silently wraps your modules into an IIFE to provide module-scoped variables (例如 moduleexports)。这就是你看到的 arguments (并不是说 arguments 在箭头函数中不存在,它的词法范围就像 this 一样,所以在在这两种情况下,它都指向周围的 arguments²)。


²证明:

function surrounding() {
  (() => console.log(arguments))();
}

surrounding("you see");

关于javascript - 在 Node js 控制台和浏览器之间的箭头函数中使用参数时的不同输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57745096/

相关文章:

angularjs - 使用 multer、ng-file-upload、Angular 和 Node 上传多个文件,并将动态表单数据绑定(bind)到每个文件

python - React - 具有动态 'output' 的 Django webpack 配置

ios - 如何使用户无需在 URL 前键入 "http://"?

JavaScript:如何迭代过滤数组?

javascript - 无法在一次运行中删除多个数组元素

javascript - 在gruntjs中使用requirejs构建一个库,并在其他项目中使用

javascript - 谷歌翻译导致导航链接失败

node.js - 如何更改 Node 模块 "say"的音频输出设备

javascript - 如何更改浏览器后退按钮的目标网址

css - Safari 页面高度问题