获取以下代码片段。
var exec = require('child_process').exec;
var extraInfo = {'test':1,'passing':'test'};
runWithData(extraInfo);
function runWithData(passedData)
{
exec('/Users/test/Desktop/testcommand', function callback(error,stdout,stderr)
{
if (error)
{
console.log("ERROR",stderr);
}
else
{
console.log(stdout);
}
});
}
在 exec 的回调中,我希望能够访问传递的数据。直接访问 PassedData 是执行此操作的正确方法吗?如果同时处理多个函数调用,这是否会被覆盖,或者是否有办法将信息附加到回调函数中,以便与其绑定(bind)?
最佳答案
来自@jfriend00:
You can just access 'passedData' directly. It's in a parent scope which is completely accessible to you in the callback. Each function call creates a new scope and thus creates a new set of data so multiple function calls do not mess it up
另请参阅:MDN Closures
[注意:标记为社区维基,因为这主要来自其他人的评论等,我不为此声明积分。请随意编辑和改进]
关于javascript - 在内部 Javascript 回调函数中访问父函数参数的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26814552/