[英]Understanding nested callbacks and scope?
我了解有很多有关回调的文档和课程。 我已经阅读了许多这些资源,但是对于这个特定的问题,我不知道发生了什么。 而且,我认为有关此特定问题的帮助将帮助我更好地了解回调。
简而言之,我不明白为什么我可以在主要的“ readFile()”函数的一部分中访问“ ext”,但无法将其传递给该函数中的函数,即“ filterData()”函数。
感谢您的理解。
const fs = require("fs");
const path = require("path");
const dir1 = process.argv[2];
const fileType = process.argv[3];
const whenDone = function(err, data) {
if(err) {
console.log(err);
} else {
for(i = 0; i < data.length - 1; i++) {
console.log(data[i]);
}
}
}
let arr = [];
function readFile(dirName, ext, callback) {
fs.readdir(dirName, function (err, data) {
if (err) {
return callback(err, null);
}
// ext and data are defined here:
console.log(ext, data);
function filterData(ext) {
// ext and data are not defined here?
console.log(ext, data);
return data.filter(function(files) {
return arr = files.includes(ext);
console.log(arr);
});
return callback(null, arr);
}
});
}
readFile(dir1, fileType, whenDone);
您正在嵌套函数中定义参数名称ext
,该参数名ext
了上限ext
参数。 因此,您可以将其更改为其他内容,并且您将具有上级ext
参数访问权限。
原因是在嵌套函数( filterData
)中,您声明了一个名称( ext
)的参数(本质上是一个局部变量),该参数已经存在于更高范围( readFile
)中,因此,在filterData
函数的持续时间内, ext
是指传递给它的内容,而不是传递给readFile
的ext
。 这称为“隐藏”或“阴影” ,当较小的作用域声明一个已在较高作用域中声明的标识符时发生。
我已经在这里写过这个。
如果仅更改嵌套函数的参数名称,并确保在嵌套函数内引用了这些参数名称,则它将起作用:
// The parameters of a function essentially become local variables
// to that function. The names you give will exist throughout that
// function's scope.
function readFile(dirName, ext, callback) {
fs.readdir(dirName, function (err, data) {
if (err) {
return callback(err, null);
}
console.log(ext, data);
// To avoid shadowing/hiding name the nested function's
// arguments something that doesn't conflict with existing
// identifier names in the higher scope.
function filterData(ext2) {
// Now, there is no collission:
console.log(ext2, data);
return data.filter(function(files) {
return arr = files.includes(ext2);
console.log(arr);
});
return callback(null, arr);
}
});
}
这是一个简单的例子:
var x = 10; var y = 20; function foo(){ var x = true; // <-- This x shadows the one from the higher scope console.log(x,y); // true 20, not 10, 20 } foo(); console.log(x,y); // 10 20 because the scope of foo is not available here
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.