如何在javascript中访问当前范围之外的变量?

sek*_*t64 6 javascript jquery closures scope

我正在用javascript编写一个应用程序,无法弄清楚如何访问我的函数中声明的变量,在这个jquery解析中.在里面我可以访问全局变量,但我真的不想为这些值创建全局变量.

基本上我想从simulationFiles变量中的xml文档中提取文件名.我检查节点属性是否等于simName和提取xml元素中的两个字符串,我觉得它正在工作.

如何提取这些xml元素并将它们附加到局部变量?

function CsvReader(simName) {
    this.initFileName = "somepath";
    this.eventsFileName = "somepath";
    $(simulationFiles).find('simulation').each(function() {
       if ($(this).attr("name") == simName) {
           initFileName += $(this).find("init").text();
           eventsFileName += $(this).find("events").text();
       }
    });
}   
Run Code Online (Sandbox Code Playgroud)

Cᴏʀ*_*ᴏʀʏ 14

thisCsvReader函数是不相同thiseach()回调(其中相反,它是在迭代的当前元素).要在回调中访问外部函数的作用域,我们需要能够通过另一个名称引用它,您可以在外部作用域中定义它:

function CsvReader(simName) {
    this.initFileName = "somepath";
    this.eventsFileName = "somepath";
    var self = this; // reference to this in current scope
    $(simulationFiles).find('simulation').each(function() {
       if ($(this).attr("name") == simName) {
           // access the variables using self instead of this
           self.initFileName += $(this).find("init").text();
           self.eventsFileName += $(this).find("events").text();
       }
    });
}
Run Code Online (Sandbox Code Playgroud)