文档在这里
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions#No_binding_of_arguments
说箭头函数没有自己的参数对象。
所以当我们在箭头函数中使用它时,它应该是未定义的。
但是我在 nodejs console
和 browser
(Firefox Developer 70.0b2) 之间得到了不同的结果。
我在网上搜索过,但找不到官方文档。
let arrowFun = () => {
console.log(arguments);
};
arrowFun("a", "b", "c");
- 在 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 ...
}
- 在浏览器中,我得到了正确的输出:undefined
最佳答案
那是因为NodeJS silently wraps your modules into an IIFE to provide module-scoped variables (例如 module
和 exports
)。这就是你看到的 arguments
(并不是说 arguments
在箭头函数中不存在,它的词法范围就像 this
一样,所以在在这两种情况下,它都指向周围的 arguments
²)。
²证明:
function surrounding() {
(() => console.log(arguments))();
}
surrounding("you see");
关于javascript - 在 Node js 控制台和浏览器之间的箭头函数中使用参数时的不同输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57745096/