简体   繁体   English

在内部JavaScript回调函数中访问父函数参数的正确方法

[英]Correct way to access parent function parameter in inner Javascript callback function

Take the following code snippet. 采取以下代码段。

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);
        }
    });
}

Within the callback of exec I want to be able to access the passedData. 在exec的回调中,我希望能够访问passedData。 Is accessing passedData direct the correct way to do this and will this get overwritten if multiple function calls are being processed at the same time, or is there a way to attach the info into the callback function so it is tied to it? 访问passedDirect是执行此操作的正确方法,并且如果同时处理多个函数调用,是否会覆盖此信息,或者是否有方法将信息附加到回调函数中以使其与之绑定?

From @jfriend00: 来自@ jfriend00:

You can just access 'passedData' directly. 您可以直接访问“ passedData”。 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 每个函数调用都会创建一个新的作用域,从而创建一个新的数据集,因此多个函数调用不会将其弄乱

See also: MDN Closures 另请参阅: MDN闭包

[Note: Marked community wiki as this is mostly from others' comments, etc, for which I do not claim point credit. [注:标记为社区的Wiki,因为这主要来自其他人的评论等,对此我并不主张积分。 Feel free to edit and improve] 随时进行编辑和改进]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM