将函数范围传递给回调函数

Passing scope of a function to the callback function

在节点中,假设我有以下代码:-

function readDirectory(callback){
    fs.readdir('./', filterList);
}

function filterList(err,data){
    //callback is undefined
    if(err) callback(err);
    callback();
}

readDirectory(function(){
    console.log("Hi");
}

但是,如果我在 readDirectory 本身内部定义函数,则以下内容有效,因为它在同一范围内:-

function readDirectory(callback){
    fs.readdir('./', function(err,data){
        if(err) callback(err);
        callback();
    });
}

readDirectory(function(){
    console.log("Hi");
}

所以我的问题是,有没有办法将 readDirectory 的作用域传递给外部定义的回调函数?

So my question is, is there a way to pass the scope of readDirectory to the callback function that's defined outside?

不,JavaScript 有词法作用域。但是,您可以让 filterList 接受回调:

function readDirectory(callback){
    fs.readdir('./', filterList(callback));
}

function filterList(callback) {
  return function(err,data){
    if(err) callback(err);
    callback();
  };
}