admin管理员组文章数量:1401281
See the below snippets:
Snippet #1:
let fs = require("fs");
fs.readFile(process.argv[2], "utf8", (error, data) => console.log(arguments));
See the below snippets:
Snippet #1:
let fs = require("fs");
fs.readFile(process.argv[2], "utf8", (error, data) => console.log(arguments));
Snippet #2:
let fs = require("fs");
fs.readFile(process.argv[2], "utf8", (error, data) => console.log(error, data));
Expected log:
Values of (error, data)
, for example like:
null 'console.log("HELLO WORLD");\r\n'
When you try both these snippets, you will find that the Snippet #1 executes and logs some unexpected values for console.log(arguments)
but console.log(error, data)
logs proper values; values of (error, data)
.
Why and What was the value that is being logged for Snippet #1?
Share Improve this question asked Nov 5, 2016 at 8:07 Temp O'raryTemp O'rary 5,83815 gold badges53 silver badges114 bronze badges 2-
Should those snippets be runnable? Coz,
require
will not work – Rajesh Commented Nov 5, 2016 at 8:09 - See also Arrow function vs function declaration / expressions: Are they equivalent / exchangeable?. – Felix Kling Commented Nov 5, 2016 at 14:59
2 Answers
Reset to default 10No binding of arguments
Arrow functions do not bind an arguments object Thus, arguments is simply a reference to the name in the enclosing scope.
From: MDN - Arrow functions
If you wish to use variadic arguments inside an arrow function, use the rest parameters syntax:
fs.readFile(process.argv[2], "utf8", (...args) => console.log(args));
@Tamas is smack on,
But a little tip for the OP, if you ever wonder what new javascript features from ES6 etc are doing. I paste the code into Babeljs.io try it out bit.
eg. Your code ->
https://babeljs.io/repl/#?babili=false&evaluate=true&lineWrap=false&presets=es2015%2Ces2015-loose%2Ces2016%2Ces2017%2Clatest%2Creact%2Cstage-0%2Cstage-1%2Cstage-2%2Cstage-3&code=fs.readFile(process.argv%5B2%5D%2C%20%22utf8%22%2C%20(error%2C%20data)%20%3D%3E%20console.log(arguments))%3B%0D%0A
and then @Tamas code ->https://babeljs.io/repl/#?babili=false&evaluate=true&lineWrap=false&presets=es2015%2Ces2015-loose%2Ces2016%2Ces2017%2Clatest%2Creact%2Cstage-0%2Cstage-1%2Cstage-2%2Cstage-3&code=fs.readFile(process.argv%5B2%5D%2C%20%22utf8%22%2C%20(...args)%20%3D%3E%20console.log(args))%3B
本文标签:
版权声明:本文标题:javascript - Value of 'arguments' of fat arrow function inside callback giving unexpected values - Stack Overflo 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744298559a2599465.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论