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

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

基本上我想从simulationFiles变量中的xml文档中提取文件名。 我检查node属性是否与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(); } }); } 

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

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

我做了一个工作演示 (我改变它使用类,所以它可以使用HTML)。

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

你可以做的最简单的改变是……将你的函数从普通(function(){})更改为箭头函数(()=> {}),它将自动获取函数的上下文它是定义的。