简体   繁体   English

在匿名函数之外访问变量

[英]Accessing variable outside of Anonymous Function

I know this is probably a duplicate but I just can't figure out how to do it (trust me i've searched, i've tried to fiddle around with the code). 我知道这可能是重复的,但我只是想不通该怎么做(相信我,我已经搜索过,我试图弄弄代码)。 I have the following code which is building a table of files that you drag and dropped in to the app. 我有以下代码正在构建一个文件表,您将它们拖放到应用程序中。

function CreateTrackTable (data, length) {

    var fs = require('fs'),
        mm = require('musicmetadata'),
        i  = 0;

    for (i; i < length; ++i) { 

        var mimeType = data.dataTransfer.files[i].type;

        if (mimeType == "audio/mp3" || mimeType == "audio/x-m4a"){

                FilePath = data.dataTransfer.files[i].path;
                var parser = mm(fs.createReadStream(FilePath));

            parser.on('metadata',  function (result) {

                if (result.picture.length == 0) {
                    $("#track-table").append('<tr path="'+ FilePath +'"><td></td></tr>');
                }else{
                    var picture = base64ArrayBuffer(result.picture[0].data);
                    $("#track-table").append('<tr path="'+ FilePath +'"><td></td></tr>');     
                }
            });
        }
    } 
}

The Problem is that the FilePath variable is accessible however it "prints-out" always the same path, not the one respected to the loop i. 问题是FilePath变量是可访问的,但是它始终“打印”相同的路径,而不是循环i所遵循的路径。

The app is builded with nodo-webkit everything quite works and this is the only problem I can't figure out. 该应用程序是使用nodo-webkit构建的,一切正常,这是我无法解决的唯一问题。

Thanks for the help! 谢谢您的帮助!

Each function created inside the loop closes over the same FilePath (ie they don't each get their own copy), which means that they'll each see whatever value that variable has whenever they execute. 在循环内创建的每个函数都将关闭相同的FilePath (即它们各自没有得到自己的副本),这意味着它们每次执行时都将看到变量具有的任何值。 To make this work how you expect, you need to arrange it so that they do each get their own copy. 为了使这项工作,你如何期望,你需要安排它,这样他们各自获得自己的拷贝。 Since JavaScript variables are scoped to the nearest enclosing function, the way to do that is to wrap the function creation in an immediately-invoked function that receives the desired value as an argument: 由于JavaScript变量的作用域是最接近的封闭函数,因此,该方法是将函数创建包装在立即调用的函数中,该函数接收所需的值作为参数:

(function(FilePath) {
    parser.on('metadata',  function (result) {
        if (result.picture.length == 0) {
            $("#track-table").append('<tr path="'+ FilePath +'"><td></td></tr>');
        } else {
            var picture = base64ArrayBuffer(result.picture[0].data);
            $("#track-table").append('<tr path="'+ FilePath +'"><td></td></tr>');     
        }
    });
})(FilePath);

In this case, each new function closes over a new FilePath , which produces the wanted result. 在这种情况下,每个新函数都将关闭一个新FilePath ,从而产生所需的结果。

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

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